Python调用subprocess执行PowerShell脚本未等待完成,如何确保等待?
解决Python等待PowerShell执行SIMION命令完成的问题
核心问题分析
subprocess.run/call 默认会等待子进程(此处为PowerShell)执行完成,但如果PowerShell内部启动的SIMION命令是异步执行的(比如启动独立进程后PowerShell直接返回),就会导致Python提前进入后续读取文件的逻辑,触发FileNotFoundError。
解决方案
1. 强制PowerShell等待SIMION进程结束
修改PowerShell命令,确保它必须等SIMION执行完成后才退出:
- 若SIMION是命令行程序,直接调用通常会阻塞执行,但如果是GUI程序或异步启动的进程,需用
Start-Process显式指定等待参数:
参数说明:Start-Process -FilePath "simion.exe" -ArgumentList "你的SIMION运行参数" -RedirectStandardOutput "out_test.txt" -Wait -NoNewWindow-Wait:强制PowerShell等待SIMION进程结束-NoNewWindow:避免弹出新的命令行窗口(可根据需求调整)-RedirectStandardOutput:将SIMION的输出重定向到目标文件
2. 正确构造Python的subprocess调用
在Python中使用subprocess.run,确保参数传递正确:
import subprocess # 替换为实际的路径和参数 simion_exe = r"C:\Program Files\SIMION\simion.exe" simion_params = "your_simion_task_params" output_file = r"C:\your\output\directory\out_test.txt" # 构造完整的PowerShell命令 ps_command = f'Start-Process -FilePath "{simion_exe}" -ArgumentList "{simion_params}" -RedirectStandardOutput "{output_file}" -Wait -NoNewWindow' # 执行命令并等待完成 subprocess.run( ["powershell", "-Command", ps_command], check=True, # 可选:命令执行失败时抛出异常,便于排查问题 shell=False # 避免shell解析歧义,推荐使用 ) # 此时可安全读取输出文件 with open(output_file, "r", encoding="utf-8") as f: output_content = f.read() print(output_content)
3. 确保路径一致性
- 始终使用绝对路径指定SIMION程序和输出文件,避免因Python脚本与PowerShell的工作目录不同,导致文件生成在非预期位置。
- 若必须使用相对路径,可通过
subprocess.run的cwd参数指定PowerShell的工作目录:subprocess.run( ["powershell", "-Command", ps_command], check=True, cwd=r"C:\your\working\directory" # 指定PowerShell的工作目录 )
4. 验证命令执行状态
添加check=True可以捕获PowerShell命令的执行错误(比如SIMION路径错误、参数无效等),避免因命令执行失败导致文件未生成,却继续执行读取逻辑。
内容的提问来源于stack exchange,提问作者Alex Marshall
相关产品推荐
相关产品推荐

