如何获取pypsexec中长时间运行命令的执行结果?
使用pypsexec异步执行命令后获取输出的方法
当你用asynchronous=True启动远程进程时,run_executable会立即返回一个RemoteProcess对象,你需要通过这个对象等待任务完成并读取输出,具体操作如下:
- 捕获
run_executable返回的进程实例 - 调用实例的
wait()方法,等待远程命令执行完毕 - 通过
stdout和stderr属性获取命令的输出和错误信息
完整代码示例:
command = "dir /b/s *.py" # 启动异步进程并保存返回的RemoteProcess对象 remote_process = client.run_executable("cmd.exe", arguments=f"/c {command}", asynchronous=True) # 等待命令执行完成 remote_process.wait() # 读取并解码输出内容(根据远程Windows编码调整,比如gbk) stdout_result = remote_process.stdout.decode('utf-8') stderr_result = remote_process.stderr.decode('utf-8') # 处理输出 print("文件列表:") print(stdout_result) if stderr_result: print("执行错误:") print(stderr_result)
注意事项
- 不调用
wait()直接读取输出,可能只能获取部分内容或为空,因为进程可能还在运行 - 若输出出现乱码,可将解码编码换成
gbk(Windows默认编码) - 如需终止正在运行的异步进程,可调用
remote_process.kill()方法
内容的提问来源于stack exchange,提问作者shn
相关产品推荐
相关产品推荐

