简体   繁体   中英

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. However, the kill() function is executed before the update starts.

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

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. 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 .

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM