![](/img/trans.png)
[英]Wait for initiator to logon before continue with QuickFix in python
[英]How to find which file was the “initiator” Python
情况:我们知道下面将检查脚本是否已被直接调用。
if __name__ == '__main__':
print "Called directly"
else:
print "Imported by other python files"
问题: else
子句只是一个通用子句,只要脚本没有直接调用就会运行。
问题:如果没有直接调用,有没有办法获取导入的文件?
附加信息:下面是我想象代码的例子,只是我不知道在<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"
您可能希望了解几种不同的方法,具体取决于您要完成的任务。
inspect
模块有一个getfile()
函数,可用于确定当前正在执行的函数的名称。
例:
#!/usr/bin/env python3
import inspect
print(inspect.getfile(inspect.currentframe()))
结果:
test.py
要找出用于执行脚本的命令行参数,您需要使用sys.argv
例:
#!/usr/bin/env python3
import sys
print(sys.argv)
使用./test.py abc
调用时的结果:
['./test.py', 'a', 'b', 'c']
使用python3 test.py abc
调用时的结果:
['test.py', 'a', 'b', 'c']
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.