如何通过Python在os.system打开的unit shell提示符中执行命令?
如何在Python中通过
unit run启动的shell里执行命令 方案1:使用subprocess.Popen处理交互式输入
os.system对交互式进程的控制能力有限,推荐用subprocess模块直接向目标shell的标准输入写入命令:
import subprocess # 拼接启动命令(用列表形式避免字符串转义问题) start_cmd = ["unit", "run", directoryPath, "urun", "shell"] # 启动进程并打开标准输入管道 proc = subprocess.Popen(start_cmd, stdin=subprocess.PIPE, text=True) # 向目标shell发送要执行的命令,末尾加换行符模拟用户回车 proc.stdin.write("your_target_command\n") proc.stdin.flush() # 关闭输入管道并等待进程结束 proc.stdin.close() proc.wait()
方案2:检查urun shell的命令行参数格式
你之前用的/c是Windows CMD的参数,urun shell可能遵循类Unix工具的参数规范,试试-c参数直接指定命令:
import os # 用-c参数直接传递要执行的命令 os.system(f"unit run {directoryPath} urun shell -c 'your_target_command'")
如果urun shell支持直接将命令作为位置参数传入,也可以尝试:
os.system(f"unit run {directoryPath} urun shell your_target_command")
额外提示
- 如果
directoryPath包含空格或特殊字符,需要用引号包裹:f'"{directoryPath}"' - 用
subprocess还能捕获命令的输出和错误信息,方便调试:result = subprocess.run(start_cmd, input="your_target_command\n", text=True, capture_output=True) print(result.stdout) print(result.stderr)
内容的提问来源于stack exchange,提问作者Abhishek Nagare
相关产品推荐
相关产品推荐

