gpt4 book ai didi

Python 子进程 popen 管道

转载 作者:行者123 更新时间:2023-12-01 04:28:35 25 4
gpt4 key购买 nike

我正在尝试在 python 中发出命令并读取输入并将其解析回来。这是我尝试发出的命令(在命令行上运行时的示例)

-bash-3.2$ echo "passthru TST,1234" | ./vsh -a 127.0.0.1 -p 7000
PASSTHRU TST,1234
udp_send_command: timed out waiting for response
-bash-3.2$

我正在尝试使用 python 子进程

            vsh_command = ' "passthru ' + cmd + '" | ./vsh -a ' + ip_address + ' -p ' + port
print vsh_command
new_command = ['echo', vsh_command]
print new_command
proc = subprocess.Popen(new_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
print '1'
out_2, err = proc.communicate()
print out_2
print '2'
rcv = out_2.splitlines()
print '3'
for r in rcv:
print ' ' + r
print '4'

`

 "passthru TST,1234" | ./vsh -a 127.0.0.1 -p 7000
['echo', ' "passthru TST,1234" | ./vsh -a 127.0.0.1 -p 7000']
1


2
3

4

是一个|子进程无法使用命令?如果是这样,还有另一种方法可以运行此 shell 命令并获取输入吗?

更新:(使用 shell=true 命令的单个字符串)

`vsh_command = 'echo "passthru ' + cmd + '" | ./vsh -a ' + ip_address + ' -p ' + port
print vsh_command
proc = subprocess.Popen(vsh_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
print '1'
out_2, err = proc.communicate()
print out_2
print '2'
rcv = out_2.splitlines()
print '3'
for r in rcv:
print ' ' + r
print '4'

`

运行(python 脚本)

echo "passthru TST,1234" | ./vsh -a 127.0.0.1 -p 7000
1
PASSTHRU TST,1234

2
3
PASSTHRU TST,1234
4
SUCCESS

仍然不完全是我想要的,看起来它只是执行 echo 命令而不是管道

编辑#2

            p = Popen(["./vsh", "-a", ip_address, "-p", str(port)],stdin=PIPE, stdout=PIPE)
out, err = p.communicate("passthru TST,1234")
print '----------'
print out

输出:

-bash-3.2$ python mfd_ascii_test.py
udp_send_command: timed out waiting for response
----------
PASSTHRU TST,1234

-bash-3.2$

out是echo的结果,而不是'udp_send_command: timed out waiting for response'

最佳答案

如果要将输出从一个进程通过管道传送到另一个进程,可以将标准输出从一个进程传送到另一个进程的标准输入:

from subprocess import PIPE,Popen

p1 = Popen(["echo", "passthru TST,1234"],stdout=PIPE)

p2 = Popen(["./vsh", "-a", "127.0.0.1", "-p", "7000"],stdin=p1.stdout,stdout=PIPE,stderr=PIPE)
p1.stdout.close()
out, err = p2.communicate()

如果您想使用管道字符,则需要设置 shell=True 并传递单个字符串:

from subprocess import check_output

out = check_output('echo "passthru TST,1234" | ./vsh -a 127.0.0.1 -p 7000',shell=True)

关于Python 子进程 popen 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32749152/

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