简体   繁体   English

如何找到哪个文件是“启动器”Python

[英]How to find which file was the “initiator” Python

Situation: We know that the below will check if the script has been called directly. 情况:我们知道下面将检查脚本是否已被直接调用。

if __name__ == '__main__':
    print "Called directly"

else:
    print "Imported by other python files"

Problem: The else clause is only a generic one and will run as long as the script was not called directly. 问题: else子句只是一个通用子句,只要脚本没有直接调用就会运行。

Question: Is there any way to get which file it was imported in, if it is not called directly? 问题:如果没有直接调用,有没有办法获取导入的文件?

Additional information: Below is an example of how I envisioned the code would be like, just that I do no know what to put in <something> . 附加信息:下面是我想象代码的例子,只是我不知道在<something><something>

if __name__ == '__main__':
    print "Called directly"

elif <something> == "fileA.py":
    print "Called from fileA.py"

elif <something> == "fileB.py":
    print "Called from fileB.py"

else:
    print "Called from other files"

Try this:- 试试这个:-

import sys
print sys.modules['__main__'].__file__

Refer for better answer:- How to get filename of the __main__ module in Python? 请参考更好的答案: - 如何在Python中获取__main__模块的文件名?

There are a couple different methods you may like to be aware of depending on what you're trying to accomplish. 您可能希望了解几种不同的方法,具体取决于您要完成的任务。

The inspect module has a getfile() function which can be used to determine the name of the currently-executing function. inspect模块有一个getfile()函数,可用于确定当前正在执行的函数的名称。

Example: 例:

#!/usr/bin/env python3
import inspect
print(inspect.getfile(inspect.currentframe()))

Result: 结果:

test.py

To find out which command-line arguments were used to execute a script, you'll need to use sys.argv 要找出用于执行脚本的命令行参数,您需要使用sys.argv

Example: 例:

#!/usr/bin/env python3
import sys
print(sys.argv)

Result when invoked with ./test.py abc : 使用./test.py abc调用时的结果:

['./test.py', 'a', 'b', 'c']

Result when invoked with python3 test.py abc : 使用python3 test.py abc调用时的结果:

['test.py', 'a', 'b', 'c']

Hope this helps! 希望这可以帮助!

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

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