Python 3.x 在python中与子流程交互的最佳实践是什么
我正在构建一个应用程序,用于在另一个软件中处理大量数据。为了自动控制其他软件,我使用的是pyautoit,一切正常,除了由外部软件引起的应用程序错误,这些错误时有发生 为了处理这些情况,我建立了一个看门狗:Python 3.x 在python中与子流程交互的最佳实践是什么,python-3.x,subprocess,Python 3.x,Subprocess,我正在构建一个应用程序,用于在另一个软件中处理大量数据。为了自动控制其他软件,我使用的是pyautoit,一切正常,除了由外部软件引起的应用程序错误,这些错误时有发生 为了处理这些情况,我建立了一个看门狗: 它使用子流程中的批量作业启动脚本 process = subprocess.Popen(['python', job_script, src_path], stdout=subprocess.PIPE, stderr
- 它使用子流程中的批量作业启动脚本
process = subprocess.Popen(['python', job_script, src_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
- 它使用winevt.EventLog模块侦听系统事件
EventLog.Subscribe('System', 'Event/System[Level<=2]', handle_event)
EventLog.Subscribe('System','Event/System[Level我相信最好的答案可能在这里: 这些属性应该允许在不同的过程之间非常容易地进行适当的通信,并且没有任何其他依赖性 请注意,如果其他进程可能导致问题,Popen.communicate()可能更适合 编辑以添加示例脚本: main.py
Doc2.pyfrom subprocess import * import sys def check_output(p): out = p.stdout.readline() return out def send_data(p, data): p.stdin.write(bytes(f'{data}\r\n', 'utf8')) # auto newline p.stdin.flush() def initiate(p): #p.stdin.write(bytes('init\r\n', 'utf8')) # function to send first communication #p.stdin.flush() send_data(p, 'init') return check_output(p) def test(p, data): send_data(p, data) return check_output(p) def main() exe_name = 'Doc2.py' p = Popen([sys.executable, exe_name], stdout=PIPE, stderr=STDOUT, stdin=PIPE) print(initiate(p)) print(test(p, 'test')) print(test(p, 'test2')) # testing responses print(test(p, 'test3')) if __name__ == '__main__': main()
import sys, time, random def recv_data(): return sys.stdin.readline() def send_data(data): print(data) while 1: d = recv_data() #print(f'd: {d}') if d.strip() == 'test': send_data('return') elif d.strip() == 'init': send_data('Acknowledge') else: send_data('Failed')
这是我能想到的最好的跨进程通信方法。还要确保所有请求和响应都不包含换行符,否则代码会中断。谢谢,听起来不错))但是我如何才能在子进程内通过stdin发送消息?意思是,在该进程内运行的脚本中?如何实现?我相信您应该使用sys.stdin从流中读取。我将测试一个程序,稍后给出一些示例代码。