【问题标题】:stdin stdout python: how to reuse the same input file twice?stdin stdout python:如何重复使用相同的输入文件两次?
【发布时间】:2014-02-20 14:52:26
【问题描述】:

我对 Python 很陌生,甚至对 stdin 标准输出方法也很陌生。不过,我需要使我的脚本可用于 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 = 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

当我尝试向它添加标准输入标准输出时,我首先遇到了先读取相同输入文件的问题,因此进行了一些更改,以便它实际上只打开一次。这是我修改后的 main():

            filename = sys.argv[1]
            filename_out = sys.argv[2]

            if filename == '-':
               filename = sys.stdin
            else:
                input_file = open(filename, 'rU')


            if filename_out == '-':
                filename_out = sys.stdout
                file_new = filename_out
            else:
                file_new = open(filename_out, 'w')

            input_file = open(filename, 'rU')
            tree = etree.fromstring(input_file)
            extract(tree)

            change_class(input_file)

            for x in newlist:

                if '\n' in x:                   
                   x = x.replace('\n', '')                
                print>>file_new, x

然后我像这样运行我的脚本:

./myscript.py --volumeid 输出文件

我收到了这个错误信息:

Traceback (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

我做错了什么?

【问题讨论】:

  • 问题是你想要做的:open(sys.stdin)

标签: python stdout stdin


【解决方案1】:

您正在尝试使用打开的文件对象作为文件名:

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)

您必须更改 change_class 来处理字符串,而不是打开的文件对象。

【讨论】:

  • 我已经按照你写的做了,现在我有这个错误信息:UnicodeDecodeError: 'utf8' codec can't decode byte 0xe2 in position 0: unexpected end of data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多