如何从PyCharm中从Bash调用的Python 2.7脚本打印? [英] How do I print from a Python 2.7 script invoked from Bash within PyCharm?

查看:116
本文介绍了如何从PyCharm中从Bash调用的Python 2.7脚本打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我的Python脚本test.py包含

For example if I have a python script test.py containing

import time

print 'foo'
time.sleep(5)

print 'bar'
time.sleep(5)

和一个包含以下内容的shell脚本run_test.sh

and a shell script run_test.sh containing

#!/usr/bin/env bash

python test.py

然后在PyCharm(2016.1)中运行后者(例如,使用运行"菜单项),直到整个脚本完成(大约10秒钟后)才输出任何输出.

then running the latter (using the Run menu item for example) from within PyCharm (2016.1) prints no output until the entire script has completed (after about 10 seconds).

当我的shell脚本运行时,是否有一种打印输出的方法?

Is there a way to print output as my shell script runs?

推荐答案

看起来您需要显式刷新缓冲区:

Looks like you need to explicitly flush the buffer:

import sys

print 'foo'
sys.stdout.flush()
time.sleep(5)

print 'bar'
sys.stdout.flush()
time.sleep(5)

请参见禁用输出缓冲,以了解每次打印后自动刷新的Python 2解决方案.

See Disable output buffering for Python 2 solutions that auto-flush after every print.

在您的情况下,由于您控制运行Python的bash文件,因此只需添加-u或设置PYTHONUNBUFFERED=1:

In your case, since you control the bash file that runs Python, just add -u or set PYTHONUNBUFFERED=1:

python -u test.py

PYTHONUNBUFFERED=1 python test.py

这篇关于如何从PyCharm中从Bash调用的Python 2.7脚本打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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