【发布时间】: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