Я провел небольшое исследование и решил проблему с помощью подпроцесса.
#!/usr/bin/python
#
#
#
import sys
import os
import subprocess
import serial
command1 = ['ssh','user@10.40.20.46']
command2 = ['cd','/workspace/mset-utils/tests']
command3 = ['sudo','./reboot_board.py']
command4 = ['python', '-m','serial.tools.list_ports', '-v']
cmd_and = ['&&']
#commands = command1 + command2 + command3 + cmd_and +
command4
''' getting same output as running at command line
$ sudo ./reboot_board.py
Traceback (most recent call last):
File "./reboot_board.py", line 44, in <module>
mode = argv[1]
IndexError: list index out of range
----> have to reset the connection
'''
commands = command1 + command2 + cmd_and + command4
''' getting expected response
$ python Test_code_Popen_serial_connection_3_14_20.py
user@10.40.20.46's password:
5 ports found
/dev/ttyAMA0
desc: ttyAMA0
hwid: 3f201000.serial
/dev/ttyUSB0
desc: Quad RS232-HS
hwid: USB VID:PID=0403:6011 LOCATION=1-1.2:1.0
/dev/ttyUSB1
desc: Quad RS232-HS
hwid: USB VID:PID=0403:6011 LOCATION=1-1.2:1.1
/dev/ttyUSB2
desc: Quad RS232-HS
hwid: USB VID:PID=0403:6011 LOCATION=1-1.2:1.2
/dev/ttyUSB3
desc: Quad RS232-HS
hwid: USB VID:PID=0403:6011 LOCATION=1-1.2:1.3
'''
process = subprocess.Popen(commands,
stdout=subprocess.PIPE,
universal_newlines=True)
while True:
output = process.stdout.readline()
print(output.strip())
# Do something else
return_code = process.poll()
if return_code is not None:
print('RETURN CODE', return_code)
# Process has finished, read rest of the output
for output in process.stdout.readlines():
print(output.strip())
break