[英]kill subprocess.Popen().write after the process is finished
I am trying to update the router with a python script with only one ssh call.我正在尝试使用只有一个 ssh 调用的 python 脚本来更新路由器。 However, the kill() function is executed before the update starts.
但是,kill() 函数在更新开始之前执行。
process_1 = f' opkg update'
process_2 = f' echo process 2'
cmds = [
f'{process_1}\n',
f'{process_2}'
]
proc = subprocess.Popen(["ssh", "root@192.168.1.1"], stdin=subprocess.PIPE)
for cmd in cmds:
proc.stdin.write(f'{cmd}'.encode())
proc.stdin.flush()
proc.stdin.close()
proc.kill()
Solution解决方案
.wait() is the method I was looking for .wait() 是我正在寻找的方法
process_1 = f' opkg update'
process_2 = f' echo process 2'
cmds = [
f'{process_1}\n',
f'{process_2}'
]
proc = subprocess.Popen(["ssh", "root@192.168.1.1"], stdin=subprocess.PIPE)
for cmd in cmds:
proc.stdin.write(f'{cmd}'.encode())
proc.stdin.flush()
proc.stdin.close()
proc.wait()
Passing commands to standard input of ssh
is somewhat finicky.将命令传递给
ssh
的标准输入有点挑剔。 A much better solution is to switch to Paramiko, but if your needs are simple, just refactor to pass the commands as arguments to ssh
.一个更好的解决方案是切换到 Paramiko,但如果您的需求很简单,只需重构以将命令作为参数传递给
ssh
。
result = subprocess.run(
["ssh", "root@192.168.1.1",
"\n".join(cmds)],
check=True)
Like the documentation already tells you, you should generally prefer subprocess.run
(or its legacy siblings check_call
, check_output
, etc) over Popen
whenever you can.就像文档已经告诉您的那样,您通常应该尽可能喜欢
subprocess.run
(或它的旧兄弟check_call
、 check_output
等)而不是Popen
。 The problems you were experiencing is one of the symptoms, and of course, the fixed code is also much shorter and easier to understand.您遇到的问题是症状之一,当然,固定代码也更短且更易于理解。
As a further aside, f'{thing}'
is just a really clumsy way to write thing
(or str(thing)
if thing
isn't already a string).另外,
f'{thing}'
只是一种非常笨拙的编写方式(如果thing
还不是字符串thing
则为str(thing)
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.