将stdin和参数传递给脚本

时间:2019-01-15 22:37:56

标签: python python-2.7

我想将stdin(带有记录的文本文件)和参数都传递给python程序。

cat names.txt | python myprogram.py 1

代码是:

#myprogram 

import fileinput,sys
fd = fileinput.input()
for line in fd:
    print line
    print "next\n"
fd.close()
print sys.argv[:] .   #ERROR 

File "test_input.py", line 5, in <module>
 for line in fd:
File "/anaconda3/envs/python2/lib/python2.7/fileinput.py", line 237, in next
 line = self._readline()
File "/anaconda3/envs/python2/lib/python2.7/fileinput.py", line 339, in _readline
 self._file = open(self._filename, self._mode)
IOError: [Errno 2] No such file or directory: '1'

当我分别编码以捕获stdin和参数时,它们可以工作。但是在一起,它们给我一个错误。

#myprogram
import fileinput,sys
fd = fileinput.input()
for line in fd:
    print line
fd.close() .  #command "cat names.txt | python myprogram.py" outputs names

#myprogram
import fileinput,sys
print sys.argv[1] . #Command "python myprogram.py 1"   outputs 1

很抱歉遇到这样一个菜鸟问题。根据this answer,这两个问题都应独立对待并且应该可以工作。我无法在线找到答案,因此希望有人可以在这里为我提供帮助。谢谢

1 个答案:

答案 0 :(得分:3)

如果以交互方式导入fileinput和help(fileinput),则可以得到一个很好解释的答案。我在这里重现有趣的部分:

典型用法是:

    import fileinput
    for line in fileinput.input():
        process(line)

This iterates over the lines of all files listed in sys.argv[1:],
defaulting to sys.stdin if the list is empty.  If a filename is '-' it
is also replaced by sys.stdin.  To specify an alternative list of
filenames, pass it as the argument to input().  A single file name is
also allowed.