如何使用Python执行带命令行输入的Shell程序并传递交互指令?
问题根本原因
os.system() 是同步阻塞执行的,你运行./build/csp-client -k/dev/ttyUSB1之后,Python会一直等待csp-client进程主动退出才会执行下一行的cmp ident,而cmp ident本身是csp-client的内部交互指令,不是系统级命令,就算执行也是调用系统自带的cmp工具,根本传不到csp-client的标准输入里,自然不会有对应输出。
解决方案
用Python标准库的subprocess.Popen接管csp-client的标准输入输出流,直接把指令写入进程的stdin即可。
示例实现代码
import subprocess import os WORK_DIR = '/home/augustin/workspaceGS/gs-sw-nanosoft-product-interface-application-2.5.1' os.chdir(WORK_DIR) # 先执行编译,check_call会在编译失败时报错终止,避免后续无效操作 subprocess.check_call('./waf') # 启动csp-client,用管道接管输入输出流,universal_newlines=True支持直接传字符串无需手动转字节 csp_proc = subprocess.Popen( ['./build/csp-client', '-k/dev/ttyUSB1'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, bufsize=1 ) # 向csp-client写入指令,必须加换行符,等价于你在Shell里输完指令按回车 csp_proc.stdin.write('cmp ident\n') csp_proc.stdin.flush() # 强制刷新缓冲区,确保指令立刻发送到子进程 # 读取运行输出,timeout可根据指令执行时长调整,避免进程卡死 output, error = csp_proc.communicate(timeout=10) print("程序输出:") print(output) if error: print("错误输出:") print(error)
注意事项
- 如果需要连续发送多条指令,不要直接用
communicate(),可以逐行写入stdin之后逐行读取stdout,避免缓冲区堵塞 - 如果csp-client输出有固定提示符比如
csp-client#,可以在读输出时判断到提示符后再发送下一条指令,运行逻辑更稳定 - 使用完毕后建议调用
csp_proc.terminate()主动关闭进程,避免后台残留孤儿进程
内容的提问来源于stack exchange,提问作者BigPhac
相关产品推荐
相关产品推荐

