python获取控制台输出内容_在python中获取当前控制台输出(Get current console output in python)...

本文探讨如何在Python中获取当前程序的控制台输出,包括使用StringIO重定向stdout和实现自定义类来保存输出内容,同时保持控制台显示。解决方案适用于Windows和Linux平台。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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__中定

### 如何使用Python解析和处理常见日志文件格式 #### 日志配置与记录 在 Python 中,`logging` 是标准库中用于记录应用程序运行状态的重要模块。它支持多种日志级别(DEBUG, INFO, WARNING, ERROR, CRITICAL),允许开发者灵活定义日志输出的位置、格式等内容[^1]。 以下是简单的 `logging` 配置示例: ```python import logging # 创建 logger 对象 logger = logging.getLogger('example_logger') logger.setLevel(logging.DEBUG) # 定义 handler 输出日志到控制台 console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) # 定义 handler 输出日志到文件 file_handler = logging.FileHandler('app.log', mode='w') # 'w' 表示覆盖模式 file_handler.setLevel(logging.DEBUG) # 设置日志格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) file_handler.setFormatter(formatter) # 添加 handlers 到 logger logger.addHandler(console_handler) logger.addHandler(file_handler) # 记录不同级别的日志消息 logger.debug("这是一个调试信息") logger.info("这是一个提示信息") logger.warning("这是一个警告信息") logger.error("这是一个错误信息") logger.critical("这是一个严重错误信息") ``` 此代码片段展示了如何创建一个带有多个处理器的日志系统,分别向控制台和文件写入不同的日志内容[^2]。 --- #### 结构化日志数据分析 当需要对大量日志数据进行分析时,可以借助 Pandas 库将其转换为 DataFrame 并执行进一步操作。例如,假设我们有一个 Nginx 日志文件,其每行格式如下所示: ``` 192.168.1.1 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 1024 "-" "Mozilla/5.0" ``` 可以通过正则表达式提取字段,并加载至 Pandas 数据框中: ```python import re import pandas as pd def parse_nginx_log(log_line): pattern = r'(\S+) \S+ \S+ \[(.*?)\] "(.*?)" (\d{3}) (\d+)' match = re.match(pattern, log_line) if match: ip_address, timestamp, request, status_code, size = match.groups() return { 'IP': ip_address, 'Timestamp': timestamp, 'Request': request, 'Status Code': int(status_code), 'Size (Bytes)': int(size) } return None # 假设读取日志文件 with open('access.log', 'r') as f: lines = f.readlines() data = [] for line in lines: parsed_data = parse_nginx_log(line.strip()) if parsed_data: data.append(parsed_data) df = pd.DataFrame(data) print(df.head()) # 显示前几条记录 ``` 上述脚本实现了从原始日志文件中提取 IP 地址、时间戳、请求方法、响应码等关键信息的功能[^3]。 --- #### 处理超大日志文件 对于非常庞大的日志文件,单线程逐行读取可能效率低下。此时可采用多线程或多进程方式加速解析过程。以下是一个基于多线程的简单实现: ```python from concurrent.futures import ThreadPoolExecutor import os def process_chunk(chunk_filename): with open(chunk_filename, 'r') as chunk_file: for line in chunk_file: result = parse_nginx_log(line.strip()) if result: save_to_database(result) # 自定义保存函数 def split_large_file(input_filepath, output_dir, num_chunks=10): """ 将大文件分割成若干个小文件 """ file_size = os.path.getsize(input_filepath) chunk_size = file_size // num_chunks with open(input_filepath, 'rb') as src: current_chunk_index = 0 while True: content = src.read(chunk_size) if not content: break with open(f"{output_dir}/chunk_{current_chunk_index}.txt", 'wb') as dst: dst.write(content) current_chunk_index += 1 split_large_file('large_access.log', './chunks/', num_chunks=50) # 启动多线程池处理分片后的日志文件 executor = ThreadPoolExecutor(max_workers=10) for i in range(50): # 根据实际分片数量调整循环次数 executor.submit(process_chunk, f"./chunks/chunk_{i}.txt") executor.shutdown(wait=True) ``` 该部分利用了并发机制来提升性能,同时注意合理分配资源以避免过载问题[^5]。 --- #### 时间戳转化 某些情况下,日志中的时间表示形式并不便于后续计算或展示。因此需将字符串型时间转为 Unix 时间戳或其他标准化格式。例如针对 Nginx 默认日期样式 `[dd/Mon/yyyy:HH:mm:ss Z]` 可做如下变换: ```python from datetime import datetime timestamp_str = "[10/Oct/2023:13:55:36 +0000]" format_pattern = "%d/%b/%Y:%H:%M:%S %z" converted_timestamp = datetime.strptime(timestamp_str.strip('[]'), format_pattern).timestamp() print(converted_timestamp) # 打印浮点数形式的时间戳 ``` 这段代码演示了如何依据指定模板解析并重新编码时间值[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值