我相对于 python,我正在尝试编写一个 python 脚本,可以将命令或其他脚本的输出通过管道传输到该脚本。
example command | python_sript.py
在python脚本中,我将基本上分析命令的输出并将其保存到文件中。
我以为我可以通过将 sys.stdin 重定向到 subprocess.PIPE 来做到这一点,但它没有用。
sys.stdin = subprocess.PIPE
有人可以建议我应该如何处理这个问题吗?
如果命令或脚本以比 python 脚本可以处理的速度更快的速度传输数据,会发生什么。
注意:当我使用这个脚本时
import sys
data = sys.stdin.readline()
print(data)
我明白了
D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
data = sys.stdin.readline()
AttributeError: 'NoneType' object has no attribute 'readline'
当我使用它时
import sys
data = input()
print(data)
我明白了
D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
data = input()
RuntimeError: input(): lost sys.stdin
最佳答案
在(旧)Windows 上,当您使用管道时,您需要默认使用 python
可执行文件调用 python 脚本 due to NT redirection bug :
D:\> echo "test" | python tee.py
之后
sys.stdin
、 raw_input()
、 fileinput.input()
应该按预期工作。关于python - 将命令或脚本输出到另一个 python 脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4196969/