我注意到两种不同的行为,两种方法应该产生相同的结果.
目标 – 使用子进程模块执行外部程序,发送一些数据并读取结果.
外部程序是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小时内删除。
留言与评论(共有 0 条评论) |