![](/img/trans.png)
[英]How do I pass variable command line arguments for a python script, that runs from a batch file?
[英]How do I pass arguments from command line to the python script to read and update values of certain keys present in a json file
我在 json 文件中有某些数据(例如 example.json),
例如.json
data = {
'name' : 'Williams',
'working': False,
'college': ['NYU','SU','OU'],
'NYU' : {
'student' : True,
'professor': False,
'years' : {
'fresher' : '1',
'sophomore': '2',
'final' : '3'
}
}
}
我希望编写一个代码,其中我可以在命令行上给出 arguments,即假设如果脚本保存在文件“script.py”中,那么,
在终端中:如果我输入*$ python3* script.py --get name --get NYU.student
然后它输出name=Williams
NYU.student=True
如果我输入*$ python3* script.py' --set name=Tom --set NYU.student=False
然后,它将字典中的 name 和 NYU.student 键更新为 Tom 和 False,并在命令行上输出NYU.student=Tom
和NYU.student=False
。
我已经为 python 脚本(即 script.py)尝试了以下代码
脚本.py
import json
import pprint
import argparse
if __name__== "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--get", help="first command")
parser.add_argument("--set", help="second command")
args=parser.parse_args()
with open('example.json','r') as read_file:
data=json.load(read_file)
if args.set == None:
key = ' '.join(args.get[:])
path = key.split('.')
now = data
for k in path:
if k in now:
now = now[k]
else:
print('Error: Invalid Key')
print(now)
elif args.get == Null:
key, value = ' '.join(args.set[:]).split('=')
path = key.split('.')
now = data
for k in path[:-1]:
if k in now:
now = now[k]
else:
print('Error: Invalid Key')
now[path[-1]] = value
with open('example.json','w') as write_file: #To write the updated data back to the same file
json.dump(data,write_file,indent=2)
但是,我的脚本没有按预期工作? 请帮我写剧本
您的代码存在以下问题:
key = ''.join(arg[:])
--get
或--set
值,脚本也只会获得一个值。 将action="append"
到第 9 行和第 10 行将解决该问题。parser.add_argument("--get", help="first command", action="append")
parser.add_argument("--set", help="second command", action="append")
完整代码:
import json
import pprint
import argparse
if __name__== "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--get", help="first command", action="append")
parser.add_argument("--set", help="second command", action="append")
args=parser.parse_args()
try:
with open('example.json','r') as read_file:
data=json.load(read_file)
except IOError:
print("ERROR: File not found")
exit()
if args.set == None:
for arg in args.get:
key = ''.join(arg[:])
path = key.split('.')
now = data
for k in path:
if k in now:
now = now[k]
else:
print('Error: Invalid Key')
print(f"{arg} = {now}")
elif args.get == None:
for arg in args.set:
key, value = ''.join(arg[:]).split('=')
path = key.split('.')
now = data
for k in path[:-1]:
if k in now:
now = now[k]
else:
print('Error: Invalid Key')
print(f"{arg}")
now[path[-1]] = value
with open('example.json','w') as write_file: #To write the updated data back to the same file
json.dump(data,write_file,indent=2)
这是问题的获取部分,我希望你能继续你的作业的设置部分。 祝你好运
python test.py --get name NYU.student
import json
import pprint
import argparse
def match(data: dict, filter: str):
current = data
for f in filter.split("."):
if f not in current:
return False
current = current[f]
return current == True
if __name__== "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--get", nargs="*", help="first command")
args = parser.parse_args()
with open('example.json','r') as f:
data = json.loads(f.read())
if args.get is not None and len(args.get) == 2:
attr_name = args.get[0]
if match(data, args.get[1]):
print("{}={}".format(attr_name, data[attr_name]))
为了使用命令行通过 arguments 使用python3 中的 sys 模块。 sys 模块读取命令行 arguments 作为字符串列表。 列表中的第一个元素始终是文件的名称,后续元素是 arg1、arg2..... 等等。
希望下面的例子有助于理解 sys 模块的用法。
示例命令:
python filename.py 1 thisisargument2 4
对应代码
import sys
# Note that all the command line args will be treated as strings
# Thus type casting will be needed for proper usage
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
print(sys.argv[3])
对应Output
filename.py
1
thisisargument2
4
另外,请在 stackoverflow 上发布问题之前进行彻底的谷歌搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.