stdin stdout python: how to reuse the same input file twice?

前端 未结 1 1041
误落风尘
误落风尘 2021-01-27 02:09

I am quite new to Python and even newer to stdin stdout method. Nevertheless I need to make my script usable for UNIX commands, in order to make it possible for example to proce

相关标签:
1条回答
  • 2021-01-27 02:30

    You are trying to use an open file object as a filename:

    filename = sys.stdin
    
    # ...
    
    input_file = open(filename, 'rU')
    

    You cannot re-read from sys.stdin anyway; you need to read all of the file into memory, then process it twice:

    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)
    

    mwhere you'll have to alter change_class to handle a string, not an open file object.

    0 讨论(0)
提交回复
热议问题