我如何将参数从命令行传递到python脚本以读取和更新json文件中存在的某些键的值

五十铃

我在json文件(例如example.json)中有某些数据,

example.json

data = {
     'name'   :  'Williams',
     'working':  False,
     'college':  ['NYU','SU','OU'],
     'NYU'    :  {
                  'student'  : True,
                  'professor': False,
                  'years'    : {
                                 'fresher'  : '1',
                                 'sophomore': '2',
                                 'final'    : '3'

                                }

                   }
   }

我希望编写一个代码,在其中可以在命令行中提供参数,即假设脚本是否保存在文件“ 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=TomNYU.student=False在命令行上输出

我已经为python脚本尝试了以下代码(即script.py)

script.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)
    

但是,我的脚本无法正常运行吗?请帮我编写脚本

哈沙娜·塞拉辛格(Harshana Serasinghe)

您的代码存在以下问题:

  1. 在第23和35行加入参数值时,请使用空格。这导致“错误键”值。删除空间将解决问题。
key = ''.join(arg[:])
  1. 您将参数定义为仅传递一个值。不多。因此,即使您传递多个--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)
   

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将参数从命令行传递到 python 中的主函数

如何将参数从命令行传递到 bazel 文件

如何将值从命令行传递到 cypress 规范文件?

将参数从命令行传递到脚本

如何将命令行参数传递到Shell脚本中?

将参数从命令行传递到PHP类和函数脚本

如何将参数从命令行传递到Gradle

如何将参数写入Power Shell中从命令行传递的文本文件中?

如何将命令行参数传递给在docker中运行的python脚本

如何将参数从命令行传递给npm和grunt?

单击python我如何从命令行读取json之类的参数

如何修改python脚本以将外部文件用作命令行中的输入?

将参数从命令行传递到C ++

从命令行将参数传递给python脚本

如何根据从命令行传递的参数打开文件并删除某些字符

如何从脚本将命令行参数传递给python文件

如何将命令行参数传递给Windows批处理文件中的程序?

如何通过makefile将参数从命令行传递到Java程序

Shell脚本:如何将脚本的命令行参数传递给它调用的命令?

在python中从命令行传递参数

将参数从Shell脚本传递到Python脚本,而不必在命令行上指定参数

如何从命令行将参数输入到 Jenkins perl 脚本中?

从命令行 python 传递值

如何将命令从Shell脚本传递到命令行

如何将python字典的某些键和值传递给HTML脚本

如何通过传递脚本名称作为参数从命令行运行不同的python脚本

如何将参数传递给ruby命令行脚本

如何将命令行参数传递给嵌套脚本?

如何将命令行参数传递给AHK脚本?