在python中获取当前控制台输出(Get current console output in python)
我想在python中获取我的程序的当前控制台输出。 运行外部程序时有很多解决方案可以获得控制台输出,但是,我找不到任何解决方案来获取当前程序的控制台输出。 我错过了什么吗? 我正在寻找一个在Windows和Linux下运行的解决方案。
例如:
print "Hello world"
output = get_console_output() # Returns "Hello World\n"
编辑:解决方案应保留控制台输出,因此只更换stdout将无法工作,因为控制台将为空
I want to get the current console output of my program in python. There are a lot of solutions to get the console output when running an external program, however, I couldn't find any solution for getting the console output of the current program. Am I missing something? I am looking for a solution which works under windows and linux.
For example:
print "Hello world"
output = get_console_output() # Returns "Hello World\n"
Edit: The solution should preserve the console output, so just replacing stdout won't work, as the console will be empty then
原文:https://stackoverflow.com/questions/31422996
2020-10-10 20:10
满意答案
如果要访问输出,则需要将标准输出stdout重定向到某处。 例如,您可以使用StringIO :
from cStringIO import StringIO
import sys
sys.stdout = buffer = StringIO()
print "Hello World"
# get output via: buffer.getvalue()
如果您更希望输出到文件,则可以直接重定向到文件:
import sys
sys.stdout = open('output.txt', 'w')
print 'Hello World'
编辑:如果你想将输出附加到日志(根据评论),我建议一个自定义类:
import sys
class Log(object):
def __init__(self):
self.orgstdout = sys.stdout
self.log = open("log.txt", "a")
def write(self, msg):
self.orgstdout.write(msg)
self.log.write(msg)
sys.stdout = Log()
print('Hello World')
If you want to access the output you need to redirect the standard output stdout somewhere. You can use StringIO for this for example:
from cStringIO import StringIO
import sys
sys.stdout = buffer = StringIO()
print "Hello World"
# get output via: buffer.getvalue()
If you rather want the output to a file you could instead redirect directly to a file:
import sys
sys.stdout = open('output.txt', 'w')
print 'Hello World'
Edit: If you want output to be appended to log (according to comment), I suggest a custom class:
import sys
class Log(object):
def __init__(self):
self.orgstdout = sys.stdout
self.log = open("log.txt", "a")
def write(self, msg):
self.orgstdout.write(msg)
self.log.write(msg)
sys.stdout = Log()
print('Hello World')
2015-07-15
相关问答
我想出了这个[未经测试] import sys
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush() # If you want the output to be visible immedia...
一个简单的解决方案是在字符串之前写"\r" ,而不是添加换行符; 如果字符串从不缩短这是足够的... sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()
稍微复杂的是一个进度条...这是我使用的东西: def startProgress(title):
global progress_x
sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
...
你需要在Spyder中使用IPython控制台才能工作。 您发布的示例在该控制台中对我来说工作得很好,但不是在Python中 ,它们在那里惨败。 You need to use the IPython console in Spyder for this to work. The examples you posted work fine for me in that console, but not in the Python one, where they fail miserably.
我建议使用subprocess.check_output()函数 。 此函数允许您执行任意命令/程序并将其输出捕获为Python中的字符串。 例: import subprocess
output = subprocess.check_output("command to execute", shell=True)
变量“output”现在包含命令的输出,您可以使用任何常用的字符串方法进行解析。 根据您的使用情况,您可能需要也可能不需要shell=True参数。 主要区别在于命令是在默认she...
self.process = QProcess()
self.connect(self.process, SIGNAL("readyReadStdout()"), self.readOutput)
self.connect(self.process, SIGNAL("readyReadStderr()"), self.readErrors)
tarsourcepath="sudo tar xvpf "+ self.path1
self.process.setArguments(QStringLis...
这可能不是确切的解决方案,我很确定会有更好的解决方案,但我想如果你在上一次apt-get语句之后尝试sleep ,它可能会有效。 根据您的代码: import time
subprocess.call("pip install phpserialize &> /dev/null 2>&1", shell=True)
subprocess.call("pip install requests &> /dev/null 2>&1", shell=True)
subprocess.call("apt-...
所以,我最终得到了这个小脚本: import os
import sys
import time
def main():
"""
Starts the loop check.
"""
if len(sys.argv) == 2:
filename = sys.argv[1]
while True:
# Clears the window
os.system("cls")
...
打印到控制台通常很慢,因为大多数语言都倾向于等到消息显示后再继续。 你目前的做法有很多。 如果您使用文件API,通过sys.stdout ,您可以根据需要多次write() ,并在准备好打印屏幕时调用flush() 。 您也可以尝试尽可能少地调用write() ,也许在内存中构建字符串并将它们整体输出。 但是,确实需要帧速率上限。 控制台不是一个快速的界面,它不能做高帧率。 实施上限,并使用数字。 简而言之: 尽可能少地调用write() 只有在准备渲染时才调用flush() 将帧速率限制在10,...
问题是{'class': 'secondaryInfo' }是对象的参数。 所以试试这个: from bs4 import BeautifulSoup
import requests
def imdb_spider():
url = 'http://www.imdb.com/chart/top'
source_code = requests.get(url)
plain_text = source_code.text
soup = Beautiful...
如果要访问输出,则需要将标准输出stdout重定向到某处。 例如,您可以使用StringIO : from cStringIO import StringIO
import sys
sys.stdout = buffer = StringIO()
print "Hello World"
# get output via: buffer.getvalue()
如果您更希望输出到文件,则可以直接重定向到文件: import sys
sys.stdout = open('output.txt',...
相关文章
Python 编程语言具有很高的灵活性,它支持多种编程方法,包括过程化的、面向对象的和函数式的。但最重
...
原文地址:http://blog.chinaunix.net/uid-25525723-id-3630
...
A View on Current Malware Behaviors Ulrich Bayer
...
原文地址:http://wiki.woodpecker.org.cn/moin/ObpLovelyPy
...
在本机上一切正常,不管是用ruby script/console还是script/console都能启
...
CS常用文件的安装 CS脚本参数查询 控制台常用参数查询 如何安装地图和皮肤? 武器 .mdl
...
python2和python3的区别,1.性能 Py3.0运行 pystone benchmark的速
...
Python实现用Hadoop的map/reduce对web日志进行统计 日志格式 61.160.24
...
Python的文件类型 Python有三种文件类型,分别是源代码文件、字节码文件和优化代码文件
源代
...
最新问答
如果启用了复制处理程序,请确保将其置于其中一个安全角色之后。 我见过人们做的另一件事是在不同的端口上运行admin。 最好在需要auth的页面上使用SSL,这样你就不会发送明确的密码,因此管理和复制将发生在8443上,而常规查询将在8080上发生。 如果您要签署自己的证书,请查看此有用的SO页面: 如何在特定连接上使用不同的证书? I didn't know that /admin was the context for SOLR admin because /admin does not re
第一:在您的样本中,您有: 但是你在询问 //td[@class=‘CarMiniProfile-TableHeader’] (注意TableHeader中的大写'T')。 xpath区分大小写。 第二:通过查询// td [@ class ='CarMiniProfile-TableHeader'] / td,你暗示你在外部td中有一个'td'元素,而它们是兄弟姐妹。 有很多方法可以在这里获得制作和模型
这是你的答案: http://jsfiddle.net/gPsdk/40/ .preloader-container { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; background: #FFFFFF; z-index: 5; opacity: 1; -webkit-transition: all 500ms ease-out;
问题是,在启用Outlook库引用的情况下, olMailItem是一个保留常量,我认为当您将Dim olMailItem as Outlook.MailItem ,这不是问题,但是尝试设置变量会导致问题。 以下是完整的解释: 您已将olMailItem声明为对象变量。 在赋值语句的右侧,在将其值设置为对象的实例之前,您将引用此Object 。 这基本上是一个递归错误,因为你有对象试图自己分配自己。 还有另一个潜在的错误,如果之前已经分配了olMailItem ,这个语句会引发另一个错误(可能是
我建议使用wireshark http://www.wireshark.org/通过记录(“捕获”)设备可以看到的网络流量副本来“监听”网络上发生的对话。 当您开始捕获时,数据量似乎过大,但如果您能够发现任何看起来像您的SOAP消息的片段(应该很容易发现),那么您可以通过右键单击并选择来快速过滤到该对话'关注TCP Stream'。 然后,您可以在弹出窗口中查看您编写的SOAP服务与Silverlight客户端之间的整个对话。 如果一切正常,请关闭弹出窗口。 作为一个额外的好处,wireshar
Android默认情况下不提供TextView的合理结果。 您可以使用以下库并实现适当的aligntment。 https://github.com/navabi/JustifiedTextView Android Does not provide Justified aligntment of TextView By default. You can use following library and achieve proper aligntment. https://github.com/
你的代码适合我: class apples { public static void main(String args[]) { System.out.println("Hello World!"); } } 我将它下载到c:\ temp \ apples.java。 以下是我编译和运行的方式: C:\temp>javac -cp . apples.java C:\temp>dir apples Volume in drive C is HP_PAV
12个十六进制数字(带前导0x)表示48位。 那是256 TB的虚拟地址空间。 在AMD64上阅读wiki(我假设你在上面,对吗?)架构http://en.wikipedia.org/wiki/X86-64 12 hex digits (with leading 0x) mean 48 bits. That is 256 TB of virtual address space. Read wiki on AMD64 (I assume that you are on it, right?) ar
这将取决于你想要的。 对象有两种属性:类属性和实例属性。 类属性 类属性对于类的每个实例都是相同的对象。 class MyClass: class_attribute = [] 这里已经为类定义了MyClass.class_attribute ,您可以使用它。 如果您创建MyClass实例,则每个实例都可以访问相同的class_attribute 。 实例属性 instance属性仅在创建实例时可用,并且对于类的每个实例都是唯一的。 您只能在实例上使用它们。 在方法__init__中定