我需要让我的脚本可用于UNIX命令,以便例如使用我的脚本一次处理2个输入文件。此脚本与命令行参数完美配合:
newlist = []
def f1()
....
return places
return persons
return unknown
def f2(input_file):
volume_id = sys.argv[3]
for line in input_data:
if any(place+'</dfn>' in line.decode('utf-8') for place in places):
line = line.replace('"person"', '"place"')
line = line.replace('id="', 'id="'+volume_id)
elif any(unk+'</dfn>' in line.decode('utf-8') for unk in unknown):
line = line.replace('"person"', '"undefined"')
line = line.replace('id="', 'id="'+volume_id)
elif 'class="person"' in line.decode('utf-8') and '<dfn' not in line:
line = line.replace('class="person"', '')
line = line.replace('id="', 'id="'+volume_id)
elif 'id="' in line:
line = line.replace('id="', 'id="'+volume_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
当我尝试将stdin stdout添加到它时,我首先遇到了首先读取相同输入文件的问题,并且因此制作了一些chages以便它实际上只打开一次。我修改了以下内容:
def f2(input_data) #instead of input_file
我修改了main():
filename = sys.argv[1]
filename_out = sys.argv[2]
if filename == '-':
input_file = sys.stdin
input_file_open = io.open(input_file, encoding = 'utf-8', mode = 'rb')
input_data = input_file_open
else:
input_file = open(filename, 'rU')
input_data = input_file
if filename_out == '-':
filename_out = sys.stdout
file_new = filename_out
else:
file_new = open(filename_out, 'w')
tree = etree.parse(input_data)
extract(tree)
change_class(input_data)
for x in newlist:
if '\n' in x:
x = x.replace('\n', '')
print>>file_new, x
我像这样运行我的脚本:
./myscript.py - - volumeid < inputfile > outputfile
然后我收到此错误消息:
input_file_open = io.open(input_file, encoding = 'utf-8', mode = 'rb')
TypeError: invalid file: <open file '<stdin>', mode 'r' at 0x7f9a2d5ab150>