![](/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.