[英]How do you read printed data in python?
Let's say I wrote the following python script:假设我编写了以下 python 脚本:
print("Hello")
print("Line 2")
print("Goodbye")
The output would of course be:输出当然是:
Hello
Line 2
Goodbye
After printing this data is there any way I could read it?打印这些数据后,我有什么办法可以读取它吗? In other words, can you read printed data with python?换句话说,你能用python读取打印数据吗?
You can use os.popen
.您可以使用os.popen
。 First, create your script:首先,创建您的脚本:
practice_script.py:
print("Hello")
print("Line 2")
print("Goodbye")
Then, in another script (or the interactive environment):然后,在另一个脚本(或交互环境)中:
import os
print([i.strip('\n') for i in os.popen('python practice_script.py')])
Output:输出:
['Hello', 'Line 2', 'Goodbye']
import subprocess
def system_call(command):
p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
return p.stdout.read()
This function will take a command as input and can be used as follows:此函数将命令作为输入,可以按如下方式使用:
output = str(system_call('python my_script.py'))
This can be used for mutli-line outputs and the entire output is stored in the string output
这可用于多行输出,并且整个输出存储在字符串output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.