我正在尝试通过以下命令运行我的小 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 ./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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句