简体   繁体   English

python:如何判断文件是作为导入还是主脚本执行的?

[英]python: how to tell if file executed as import vs. main script?

I'm writing a python file mylib.py 我正在编写一个python文件mylib.py

I'd like mylib.py to do something based on sys.argv if it's being executed as a script. 我希望mylib.py基于sys.argv做一些事情,如果它是作为脚本执行的话。 But if it's imported from some other script, I don't want it to do that. 但如果它是从其他脚本导入的,我不希望它这样做。

How can I tell if my python file is being imported or it's a main script? 如何判断我的python文件是否正在导入或者它是一个主脚本?

(I've seen how to do this before, but I forgot.) (我以前见过这个怎么做,但我忘了。)

if __name__ == '__main__':
    # this was run as a main script

Here is the documentation on __main__ . 这是关于__main__文档

Usually this code is placed at the bottom of a module, and one common way to keep your code clean is to create a main() function that does all of the work, and only call that function inside of the conditional. 通常这个代码放在模块的底部,保持代码清洁的一种常用方法是创建一个main()函数来完成所有的工作,并且只调用条件中的那个函数。

if __name__ == '__main__':
    # goes here only when module is being executed directly

Packages also can contain __main__ module, which is executed when you do python -m foo (or execute zipfile containing the package). 包也可以包含__main__模块,当你执行python -m foo (或执行包含包的zipfile)时执行。

By using (placing the statements you want to be executed only when the module is running as main , not imported) 通过使用(仅当模块作为main运行时才放置要执行的语句,而不是导入)

 if __name__ == "__main__":
        # this was run as a main script

Generally different statements have has to be placed in this ' if ' block like , module specific doctest call or print statements.The thing is by default (when running as main) the ' __name__ ' variable is set to " __main__ ", and otherwise (if imported ) the __name__ variable 'll get a different value, most probably the name of the module. 通常不同的语句必须放在这个' if '块中,比如模块特定的doctest调用或print语句。默认情况下(当作为main运行时)' __name__ '变量设置为“ __main__ ”,否则(如果导入__name__变量'll得到一个不同的值,很可能是模块的名称。

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

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