静默打印导入的Python脚本

use*_*147 2 python

我想将python脚本导入到另一个脚本中.

$ cat py1.py
test=("hi", "hello")

print test[0]

$ cat py2.py
from py1 import test

print test
Run Code Online (Sandbox Code Playgroud)

如果我执行py2.py:

$ python py2.py 
hi
('hi', 'hello')
Run Code Online (Sandbox Code Playgroud)

无论如何我可以静音第一个print来自的from py1 import test

我不能评论的printpy1,因为它正在使用其他地方.

Moo*_*awr 5

py1.py使用 if __name__=="__main__":

就像你的py1.py看起来像:

def main():
    test=("hi", "hello")

    print test[0]

if __name__=="__main__":
    main()  
Run Code Online (Sandbox Code Playgroud)

这将允许您仍然正常使用py1.py,但是当您导入它时,main()除非您调用它,否则它将不会运行该函数.

这解释了发生了什么

  • 这真的很可能正确答案imho ....其他一切都是"解决问题" (2认同)