Python:如何判断文件是否作为导入脚本与主脚本执行? [英] python: how to tell if file executed as import vs. main script?

查看:48
本文介绍了Python:如何判断文件是否作为导入脚本与主脚本执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写python文件 mylib.py

I'm writing a python file mylib.py

如果mylib.py作为脚本执行,我希望mylib.py基于 sys.argv 进行某些操作.但是,如果它是从其他脚本中导入的,则我不希望它这样做.

I'd like mylib.py to do something based on sys.argv if it's being executed as a script. But if it's imported from some other script, I don't want it to do that.

如何确定我的python文件是导入的还是主要脚本?

How can I tell if my python file is being imported or it's a main script?

(我之前已经看过如何做到这一点,但是我忘了.)

(I've seen how to do this before, but I forgot.)

推荐答案

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

这是 __ main __ 文档>.

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.

这篇关于Python:如何判断文件是否作为导入脚本与主脚本执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆