我使用子进程运行另一个python文件,该文件偶尔会崩溃。我想记录(PyCharm)输出中的数据并将其保存到文本文件中,以便稍后我可以找出问题所在。例如:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1254, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1106, in request
self._send_request(method, url, body, headers)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1151, in _send_request
self.endheaders(body)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1102, in endheaders
self._send_output(message_body)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 934, in _send_output
self.send(msg)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 877, in send
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 849, in connect
(self.host,self.port), self.timeout, self.source_address)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 711, in create_connection
raise err
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 702, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
这将是子进程崩溃后的输出。我想将其保存到文件中,然后重新启动子进程。看起来有点像这样:
sub = subprocess.Popen([sys.executable,...])
if sub.poll() is None:
os.system("screencapture -x crash.png")
file = open('log.txt', 'w')
#file.write() the output
start_process() #restarts the subprocess
答案 0 :(得分:0)
我认为这应该做你想做的事情
with open('log_file', 'w') as f:
sub = subprocess.Popen(..., subprocess.STDOUT=f)
retval = sub.wait()
if retval != 0:
start_process()