带有For循环的python3 stdin / file对象

时间:2014-01-30 20:32:04

标签: python python-3.x command-line stdout stdin

好的,所以我想动态地从STDIN或文件中获取输入,具体取决于命令行中给出的选项。最后我想出了这段代码:

# Process command-line options
# e.g., python3 trowley_FASTAToTab -i INFILE -o OUTFILE -s
try:
    opts, args = getopt.getopt(sys.argv[1:], 'i:o:s')
except getopt.GetoptError as err:
    # Redirect STDERR to STDOUT (insures screen display)
    sys.stdout = sys.stderr
    # Print help information
    print(str(err))
    # Print usage information
    usage()
    # Exit
    sys.exit(2)

# Define our variables
inFile = ""      # File to be read, if there is one
outFile = ""     # Outfile to write to, if there is one
keepSeq = False  # Whether or not to keep the sequence
header = ""      # The header line we will mess with
sequence = ""    # The sequence were messing with

# Parse command line options
for (opt, arg) in opts:
    if opt == "-i":
        inFile = str(arg)
    elif opt == "-o":
        outFile = str(arg)
    elif opt == "-s":
        keepSeq = True

# Lets open our outfile or put the variable to stdout
if not outFile:
    outFile = sys.stdout
else:
    outFile = open(outFile, 'w')

for line in sys.stdin:
    # Do tons of stuff here
    print(tmpHeader, file=outFile)
# Maybe some cleanup here

其中有一些奇怪的行为。如果我指定一个infile但没有outfile,它将读取该文件,执行这些操作,然后将结果输出到屏幕(它应该做什么)。

如果我放弃infile和outfile(所以输入将来自stdin),一旦我按下ctrl d(输入结束),它就什么都不做,退出脚本。当我从stdin获取输入并写入文件时,同样的事情就是不做任何事情。

我最后通过使用:

来修复它
while (1):
    line = inFile.readline()
    if not line:
        break
    # Do all my stuff here

我的问题是,为什么inFile中的for line不工作?我没有错,没有任何反应。我有什么不明确的规则吗?

0 个答案:

没有答案