简体   繁体   English

静默打印导入的Python脚本

[英]Mute printing of an imported Python script

I want to import a python script in to another script. 我想将python脚本导入到另一个脚本中。

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

print test[0]

$ cat py2.py
from py1 import test

print test

If I execute py2.py : 如果我执行py2.py

$ python py2.py 
hi
('hi', 'hello')

Can I anyway mute the first print which is coming from the from py1 import test ? 无论如何我可以将from py1 import test的第一个print静音吗?

I can't comment the print in py1 , since it is being used somewhere else. 我不能在py1评论print ,因为它正在其他地方使用。

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

So like your py1.py would look like: 就像你的py1.py看起来像:

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

    print test[0]

if __name__=="__main__":
    main()  

This will allow you to still use py1.py normally, but when you import it, it won't run the main() function unless you call it. 这将允许您仍然正常使用py1.py,但是当您导入它时,它将不会运行main()函数,除非您调用它。

This explains what's going on 这解释了发生了什么

Simply open the /dev/null device and overwrite the sys.stdout variable to that value when you need it to be quiet. 只需打开/ dev / null设备,并在需要安静时将sys.stdout变量覆盖到该值。

import os
import sys

old_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")

from py1 import test

sys.stdout = old_stdout
print test

You might want to consider changing the other script to still print when its run 'in the other place' - if you're running py1 as a shell command, try to make sure all "executable statements" in a file are inside a block. 您可能需要考虑将其他脚本更改为在“在其他位置”运行时仍然打印 - 如果您将py1作为shell命令运行,请尝试确保文件中的所有“可执行语句”都在块内。

if __name__ == "__main__":
    print test

(see What does if __name__ == "__main__": do? ) (参见__name__ ==“__ main__”是什么意思:做什么?

This would fix the underlying issue without having you do weird things (which would be redirecting the standard out, and then putting it back etc), or opening the file and executing line by line on an if block. 这将解决潜在的问题,而不会让你做奇怪的事情(将标准重定向,然后将其重新放回等),或打开文件并在if块上逐行执行。

You could implement this functionality with methods: 您可以使用以下方法实现此功能:

py1.py

test=("hi", "hello")

def print_test():
    print(test)

def print_first_index():
    print(test[0])

py2.py

import py1
py1.print_test()

As MooingRawr pointed out, this would require you to change whichever classes use py1.py to import it and call the py1.print_first_index() function which may not be to your liking. 正如MooingRawr所指出的,这将要求你改变使用py1.py导入它的类,并调用py1.print_first_index()函数,这可能不符合你的喜好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM