stdinstdoutpython:如何重复使用同一个输入文件两次?
我对Python非常陌生,甚至对stdin stdout方法也比较新。然而,我需要使我的脚本可用于UNIX命令,以便能够使用我的脚本一次处理2个输入文件。 此脚本与命令行参数配合得非常好:stdinstdoutpython:如何重复使用同一个输入文件两次?,python,stdout,stdin,Python,Stdout,Stdin,我对Python非常陌生,甚至对stdin stdout方法也比较新。然而,我需要使我的脚本可用于UNIX命令,以便能够使用我的脚本一次处理2个输入文件。 此脚本与命令行参数配合得非常好: newlist = [] def f1() .... def f2(input_file): vol_id = sys.argv[3] for line in input_file: if ... : line = line.replace('abc','def') line
newlist = []
def f1()
....
def f2(input_file):
vol_id = sys.argv[3]
for line in input_file:
if ... :
line = line.replace('abc','def')
line = line.replace('id', 'id'+vol_id)
....
newlist.append(line)
return newlist
def main():
if len(sys.argv) < 4:
print 'usage: ./myscript.py [file_in... file_out... volume_id]'
sys.exit(1)
else:
filename = sys.argv[1]
filename_out = sys.argv[2]
tree = etree.parse(filename)
extract(tree)
input_file = open(filename, 'rU')
change_class(input_file)
file_new = open(filename_out, 'w')
for x in newlist:
if '\n' in x:
x = x.replace('\n', '')
print>>file_new, x
然后我像这样运行我的脚本:
./myscript.py--volumeidTraceback (most recent call last):
File "./myscript.py", line 191, in <module>
main()
File "./myscript.py", line 175, in main
input_file = open(filename, 'rU')
TypeError: coercing to Unicode: need string or buffer, file found
回溯(最近一次呼叫最后一次):
文件“/myscript.py”,第191行,在
main()
文件“/myscript.py”,第175行,主
输入文件=打开(文件名为'rU')
TypeError:强制使用Unicode:需要字符串或缓冲区,找到文件
我做错了什么?您试图使用打开的文件对象作为文件名:
filename = sys.stdin
# ...
input_file = open(filename, 'rU')
无论如何,您不能从sys.stdin
重新读取;您需要将所有文件读入内存,然后处理两次:
if filename == '-':
input_file = sys.stdin
else:
input_file = open(filename, 'rU')
input_data = input_file.read()
tree = etree.fromstring(input_data)
extract(tree)
change_class(input_data)
M在这里,您必须更改
change\u class
来处理字符串,而不是打开的文件对象。问题是您正在尝试执行:open(sys.stdin)
我已经按照您所写的做了,现在我收到了以下错误消息:UnicodeDecodeError:“utf8”编解码器无法解码位置0处的字节0xe2:数据意外结束
if filename == '-':
input_file = sys.stdin
else:
input_file = open(filename, 'rU')
input_data = input_file.read()
tree = etree.fromstring(input_data)
extract(tree)
change_class(input_data)