首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将崩溃日志输出到txt文件

问将崩溃日志输出到txt文件
EN

Stack Overflow用户
提问于 2017-02-21 20:45:16
回答 1查看 617关注 0票数 0

我使用子进程来运行另一个python文件,这个文件经常会崩溃。我想记录(PyCharm)输出中的数据,并将其保存到一个文本文件中,以便以后找出问题所在。例如:

代码语言:javascript
复制
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

这将是子进程崩溃后的输出。我想将其保存到一个文件中,然后重新启动子进程。它看起来有点像这样:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2017-02-21 20:51:21

我认为这应该能做你想要的

代码语言:javascript
复制
with open('log_file', 'w') as f:
    sub = subprocess.Popen(..., subprocess.STDOUT=f)
    retval = sub.wait()
    if retval != 0:
        start_process()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42367722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档