【问题标题】:Getting input path and file, output path and file from command line argument in Python从 Python 中的命令行参数获取输入路径和文件、输出路径和文件
【发布时间】:2019-05-01 07:58:28
【问题描述】:

我正在尝试通过以下命令运行我的小 Python 脚本:

./pdweb_convert.py -i /path_to_file/input_file_name -o /path_to_file/output_file_name

这是我的代码:

import sys
inputfile = sys.argv[1]
outputfile = sys.argv[2]
with open(inputfile, 'r') as i, open(outputfile, 'w') as o:
    o.seek(0)
    o.truncate()
    for line in i:
        if '0x' in line:
            new_line = line[9:50]
            new_line = new_line.strip().replace(' ', '').replace('\n', '')
            try:
                new_line = bytearray.fromhex(new_line).decode("ascii")
            except Exception:
                new_line = ''
            o.write(new_line)
        else:
            o.write(line)

如果我尝试运行程序,我会在“inputfile = sys.argv[1]”行出现“IndexError: list index out of range”错误。

知道如何解决这个问题并通过键入上述命令使我的程序工作,其中 pdweb_convert 是我的脚本,输入文件将类似于 input.txt 和输出文件任何名称,因为它将在我的命令之后创建.

如果路径不存在或输入文件不存在,如何让它打印一条警告消息,正如我之前所说,我希望使用我给它的名称自动生成(创建)输出文件命令行,例如:

pdweb_convert.py -i C:\Users\Work\Documents\input.txt -o C:\Users\Work\Documents\outputexample.txt

我如何在我的脚本中编写这些代码,我今天早上开始用 Python 编程,所以我是超级初学者。谢谢!

【问题讨论】:

    标签: python input command-line arguments output


    【解决方案1】:
    python ./pdweb_convert.py -i /path_to_file/input_file_name -o /path_to_file/output_file_name
    

    (我假设你在这个命令的开头也写了 python。)

    问题是您的sys.argv 返回一个包含五个 元素的列表,而您正在调用1 和2 索引,它们是-i 和/path_to_file/input_file_name。相反,您应该调用 2 和 4 索引。当我运行您的代码时,它没有引发任何列表错误,但逻辑上它出错了

    C:\Users\Desktop>python x.py -i /path_to_file/input_file_name -o /path_to_file/output_file_name
    Traceback (most recent call last):
      File "x.py", line 4, in <module>
        with open(inputfile, 'r') as i, open(outputfile, 'w') as o:
    FileNotFoundError: [Errno 2] No such file or directory: '-i'
    

    【讨论】:

      【解决方案2】:

      Python 有一个名为 optparse 的库,让这一切变得简单

      你可以这样使用它:

      #!/usr/bin/python
      
      import optparse
      
      parser = optparse.OptionParser()
      parser.add_option('-i', help='arguments', dest='infile', action='store')
      parser.add_option('-o', help='arguments', dest='outfile', action='store')
      (opts, args) = parser.parse_args()
      print(opts)
      

      输出:

      {'infile': 'infile.txt', 'outfile': 'outfile.txt'}
      

      所以你可以抓住opts['infile'] 和opts['outfile'] 并检查这些文件是否存在于文件系统中。

      【讨论】:

        猜你喜欢
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 2020-01-07
        • 2015-10-26
        • 2017-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多