我想从脚本内部找出——我用来启动它的确切命令。我尝试了以下方法:
#!/usr/bin/env python
import sys, os
print os.path.basename(sys.argv[0]), sys.argv[1:]
但它会丢失信息:
$ 1.py -1 dfd 'gf g' "df df"
1.py ['-1', 'dfd', 'gf g', 'df df']
你看——它已经丢失了关于枯萎的信息,我在命令中使用了双引号、单引号或根本没有引号。
编辑:
这是我正在使用的。我脚本中的所有参数都有默认值,并且在 args 被解析后argparse
:
args = parser.parse_args()
我记录它们,或者如果有日志 - 覆盖它们:
logName = "." + (os.path.splitext(os.path.basename(sys.argv[0])))[0] + ".json"
if os.path.exists(logName):
print "!!! I've found log", logName
Args = bk_loads_json(logName)
for arg in Args:
exec('args.{0} = Args["{0}"]'.format(arg))
else:
print "!!! the log of args is saved to", logName
bk_saves_json(args.__dict__, logName)
defuns提到:
def bk_saves_json(myCustomDct, flNm):
"Takes dict, and writes it to the file."
FlNm = open(flNm, 'w')
tmpJsn = json.dumps(myCustomDct, sort_keys=True, indent=4)
FlNm.write(tmpJsn)
FlNm.close()
def bk_loads_json(flNm):
"Takes file of the json and returns it as a dict."
json_data=open(flNm)
data = json.load(json_data)
json_data.close()
return data