[英]python: use command line argument from file A in file B
我有一個可以接受命令行參數的python文件(例如fileA.py)。 接下來,我調用了幾個通過不同的.py文件(filea-> fileb-> filec-> fileX)的函數。 在filex中,我想使用指定給fileA的命令行參數(在這種情況下為文件)。
這是我用於命令arg解析的代碼:
p = argparse.ArgumentParser()
p.add_argument("-c", dest="configfile",help="Input configuration file")
args = p.parse_args()
configfile = args.configfile
if not (configfile):
p.print_help()
sys.exit()
f = open(configfile)
config = yaml.load(f)
我可以通過每個文件傳遞它,直到它在fileX結束為止,我已經嘗試過了,但這似乎還很不完善。 有誰有更合適的解決方案?
如果您需要在fileX.py的某些函數中使用參數,然后僅解析該函數中的參數,則不需要將其放在mainfile中。 例如-
from filex import f
f()
import argparse
def f():
p = argparse.ArgumentParser()
p.add_argument("-c", dest="configfile",help="Input configuration file")
args = p.parse_args()
configfile = args.configfile
print configfile
然后以-
mainfile.py -c someconfig_file
#it prints - someconfig_file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.