python subprocess communicate

阅读: 评论:0

python subprocess communicate

python subprocess communicate

我注意到两种不同的行为,两种方法应该产生相同的结果.

目标 – 使用子进程模块执行外部程序,发送一些数据并读取结果.

外部程序是PLINK,平台是WindowsXP,Python版本3.3.

主要想法 –

execution=["C:\Pr..\...\", "-l", username, "-pw", "***", IP]

a=subprocess.Popen(execution, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=False)

con=adline()

if (con.decode("utf-8").count("FATAL ERROR: Network error: Connection timed out")==0):

a.stdin.write(b"con rout 1n")

print(adline().decode("utf-8"))

a.stdin.write(b"infodfn")

print(adline().decode("utf-8"))

else:

print("ERROR")

a.kill()

到现在为止还挺好.

现在,我想能够做一个循环(在每次写入子进程的stdin之后),等待直到子进程的stdout的EOF,打印它,然后是另一个stdin命令,依此类推.

并且它没有工作(它永远挂起),因为PLINK进程保持活着,直到我自己杀死它,因此没有使用等待子进程的stdout到达EOF或在stdout为真时进行循环,因为它在我杀了它之前一直都是真的.

所以我每次写stdin时都决定从stdout读两次(对我来说很好) –

execution=["C:\Pr..\...\", "-l", username, "-pw", "***", IP]

a=subprocess.Popen(execution, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=False)

con=adline()

if (con.decode("utf-8").count("FATAL ERROR: Network error: Connection timed out")==0):

a.stdin.write(b"con rout 1n")

print(adline().decode("utf-8"))

print(adline().decode("utf-8")) //the extra line [1]

a.stdin.write(b"infodfn")

print(adline().decode("utf-8"))

print(adline().decode("utf-8")) //the extra line [2]

else:

print("ERROR")

a.kill()

但据我所知,第一个额外的readline()永远挂起,原因与我提到的相同.第一个额外的readline()会永远等待输出,因为唯一的输出已经在第一个readline()中读取,并且因为PLINK是活动的,所以函数只是“坐”那里等待新的输出行得到.

所以我尝试了这段代码,期待同样的挂起,因为PLINK永远不会死,直到我杀了它 –

execution=["C:\Pr..\...\", "-l", username, "-pw", "***", IP]

a=subprocess.Popen(execution, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=False)

con=adline()

if (con.decode("utf-8").count("FATAL ERROR: Network error: Connection timed out")==0):

a.stdin.write(b"con rout 1n")

print(adline().decode("utf-8"))

a.stdin.write(b"infodfn")

print(adline().decode("utf-8"))

print(amunicate()[0].decode("utf-8")) //Popenmunicate() function

else:

print("ERROR")

a.kill()

我试过这个,因为根据communic()的文档,函数等到进程结束,然后结束.此外,它从stdout读取直到EOF. (与写入和读取stdout和stdin相同)

但是,就前面的代码块而言,communic()完成并且没有挂起.

我在这里错过了什么?为什么当使用communic()PLINK结束时,但是当使用readline()时它不会?

本文发布于:2024-01-28 14:46:42,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/17064244088185.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

上一篇:centos: NVIDIA
下一篇:饭否?叽歪!
标签:python   subprocess   communicate
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23