简体   繁体   English

如何打开命令行中传递的文件 arguments

[英]How to open a file passed in the command line arguments

I have my config encoded here:我的配置在这里编码:

@staticmethod
def getConfig(env):
    pwd=os.getcwd()
    if "win" in (platform.system().lower()):
        f = open(pwd+"\config_"+env.lower()+"_data2.json")
    else:
        f = open(pwd+"/config_"+env.lower()+"_data2.json")
    config = json.load(f)
    f.close()
    return config

@staticmethod
def isWin():
    if "win" in (platform.system().lower()):
        return True
    else:
        return False

I have 2 JSON files I want my script to read, but the way it's written above it only reads 1 of them.我有 2 个 JSON 文件,我想让我的脚本读取,但上面写的方式只读取其中的 1 个。 I want to know how to change it to something like:我想知道如何将其更改为:

f = open(pwd+"\config_"+env.lower()+"_data_f'{}'.json")

so it can read either dataset1.config or dataset2.config.所以它可以读取 dataset1.config 或 dataset2.config。 I'm not sure if this is possible, but I want to do that so I can specify which file to run in the command line: python datascript.py -f dataset1.config or python datascript.py -f dataset2.config .我不确定这是否可行,但我想这样做,以便我可以在命令行中指定要运行的文件: python datascript.py -f dataset1.configpython datascript.py -f dataset2.config Do I assign that entire open() call to a variable?我是否将整个open()调用分配给一个变量?

All you need to do is parse sys.argv to get the argument of the -f flag, then concatenate the strings and pass the result to open() .您需要做的就是解析sys.argv以获取-f标志的参数,然后连接字符串并将结果传递给open() Try this:尝试这个:

import sys

### ... more code ...

    @staticmethod
    def getConfig(env):
        pwd = os.getcwd()
        file = None
        try:
            file = sys.argv[sys.argv.index('-f')+1]
        except ValueError:
            file = "data2.json"

        if "win" in (platform.system().lower()):
            f = open(pwd+"\config_"+env.lower()+"_" + file)
        else:
            f = open(pwd+"/config_"+env.lower()+"_" + file)
        config = json.load(f)
        f.close()
        return config

sys.argv.index('-f') gives the index of -f in the command line arguments, so the argument must be filename. sys.argv.index('-f')给出-f在命令行中的索引arguments,所以参数必须是文件名。 The try-except statement will provide a default value if no -f argument is given.如果没有给出-f参数,try-except 语句将提供默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM