gpt4 book ai didi

python - 将标准输入和参数传递给脚本

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:35 24 4
gpt4 key购买 nike

我想将标准输入(带有记录的文本文件)和参数传递给 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'

当我分别编写代码以捕获标准输入和参数时,它们可以正常工作。但它们一起出现时,会给我一个错误。

#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 ,两者都应该独立对待并且应该工作。我无法在网上找到答案,因此希望有人能在这里帮助我。谢谢

最佳答案

如果您以交互方式导入 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.

关于python - 将标准输入和参数传递给脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54207864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com