将命令或脚本传出到另一个python脚本

将命令或脚本传出到另一个python脚本,python,windows,pipe,Python,Windows,Pipe,我相对python而言,我正在尝试编写一个python脚本,可以将命令或其他脚本的输出通过管道传输到该脚本 example command | python_sript.py 在python脚本中,我将基本上分析命令的输出并将其保存到文件中 我想我可以通过将sys.stdin重定向到subprocess.PIPE来实现这一点,但没有成功 sys.stdin = subprocess.PIPE 有人能建议我该如何处理这个问题吗 如果命令或脚本以比python脚本更快的速度传输数据,会发生什么情

我相对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'
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
我明白了

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'
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
D:\>echo“test”| tee.py
进程试图写入不存在的管道。
回溯(最近一次呼叫最后一次):
文件“D:\Profiles\Administrator\mydocuments\Workspace\tee.py”,第3行,在
数据=输入()
运行时错误:输入():丢失sys.stdin

您似乎不太清楚管道是如何工作的。它们是由操作系统处理的,而不是由单个程序处理的——因此,如果您编写一个设计用于从管道获取输入数据的Python脚本,它应该像正常情况一样读取
stdin
,重定向将为您处理。数据将以生成的速度被消耗;如果脚本使用数据的速度比生成数据的速度慢,则这些数据将存储在缓冲区中

或者您正在尝试在两个Python脚本之间进行通信?如果是这样,还有比通过
stdin
stdout
更好的方法。问题1(从管道中读取)已被其他人回答:只需在python_script.py中读取stdin即可。操作系统通过管道处理重定向

问题2(写入/读取速度)也得到了回答:操作系统管道是缓冲的,所以这里不需要担心

问题3(堆栈跟踪):您的第一个程序运行良好你真的给出了全部代码吗

至于subprocess.PIPE:如果从运行的Python脚本中启动一个新命令,那么您实际上只想使用它,这样您就可以与子进程通信了。因为你没有这样做,这对你没有用。shell级别上的管道不构成父子进程。

在(旧)窗口上使用管道时,默认情况下需要使用
python
可执行文件调用python脚本:


在这之后,
sys.stdin
raw\u input()
fileinput.input()
应该可以按预期工作。

您推荐哪种更好的方法?@Thomas:1)将数据处理程序放在模块中并导入它。2) 生成一个单独的进程并对其进行管道处理。在编辑过程中,您似乎用
sys.stdin
做了一些愚蠢的事情。请尝试
sys.\uu stdin\uu
。关于堆栈跟踪,第一个程序对我不起作用。Python 3.1是否不支持sys.stdin.readline()?是的,这些是完整的程序。