如何通过另一个文本处理器程序使PyCharm管道python程序输出 [英] How to make PyCharm pipe python program output through another text processor program

查看:41
本文介绍了如何通过另一个文本处理器程序使PyCharm管道python程序输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现无法让 PyC​​harm 管道处理我的 Python 程序的输出.具体来说,我正在使用 bunyan (

I find no way to have PyCharm pipe process my Python program's output. Specifically, I'm using bunyan (Python Bunyan ported from Node Bunyan) from my program, it generates JSON log to stderr:

Python Code:

logger.info({'nick': 'Duke', 'age': 30, 'expertise': ['Java', 'Javascript', 'Python']},
            'Hi %(nick)s, your expertise recorded!');

Raw output:

cymp:scratches cyue$ python logging-wander.py 
{"name": "__main__", "expertise": ["Java", "Javascript", "Python"], "nick": "Duke", "age": 30, "time": "2016-08-02T18:16:12Z", "msg": "Hi Duke, your expertise recorded!", "hostname": "cymp.local", "level": 30, "pid": 1418, "v": 0}

Pipe processed output:

cymp:scratches cyue$ python logging-wander.py 2>&1 | bunyan
[2016-08-02T18:16:15Z]  INFO: __main__/1419 on cymp.local: Hi Duke, your expertise recorded! (nick=Duke, age=30)
    expertise: [
      "Java",
      "Javascript",
      "Python"
    ]

The output is piped to bunyan's command line tool for pretty print (there're even colors in terminals, but not shown here).

In WebStorm for js, I can add a local shell script as 'Node interpreter' to do the job, but for PyCharm, their's no 'Add' option for 'Python interpreter' in the 'Run/Debug Configuration' dialog, and it complains The selected file is not a valid home for PythonSDK when I try to add the shell script as 'Project Interpreter'.

I wonder any workaround can be used to have my desired result?

解决方案

Update: I end up with a better (in my sense) solution: craft a startup python stub file run-module.py like:

#!/usr/bin/env python

import os
import sys
import subprocess
import runpy

real_stderr = sys.stderr

if len(sys.argv) < 2:
    raise Exception('module name is required')

try:
    bi, bo = os.pipe()
    sys.stderr = os.fdopen(bo, 'w')
    subprocess.Popen(['bunyan', '--color'], stdin=bi, stderr=real_stderr)

    modu_name = sys.argv[1]
    sys.argv = sys.argv[1:]  # shift off run-module.py, argv[0] will be replaced by module's __main__
    runpy.run_module(modu_name, alter_sys=True)
except NameError:
    print('sys.path => %r' % sys.path, file=real_stderr)
    raise
except:
    import traceback

    traceback.print_exc(file=real_stderr)
    raise

Then run this stub as the script, with real module name as first arg.

Okay, finally I DIY an IntelliJ plugin to solve this. BunyanConsole Pretty Print while source code on GitHub BunyanConsole

这篇关于如何通过另一个文本处理器程序使PyCharm管道python程序输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆