如何在Python中将文件输出传递给变量?

时间:2022-04-04 22:09:36

How do I pipe the output of file to a variable in Python?

如何在Python中将文件输出传递给变量?

Is it possible? Say to pipe the output of netstat to a variable x in Python?

可能吗?比如说将netstat的输出传递给Python中的变量x?

3 个解决方案

#1


5  

Two parts:

Shell

netstat | python read_netstat.py

Python read_netstat.py

import sys
variable = sys.stdin.read()

That will read the output from netstat into a variable.

这将把netstat的输出读入变量。

#2


6  

It is possible. See:

有可能的。看到:

http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote

In Python 2.4 and above:

在Python 2.4及以上版本中:

from subprocess import *
x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0]

#3


2  

Take a look at the subprocess module. It allows you to start new processes, interact with them, and read their output.

看一下子进程模块。它允许您启动新进程,与它们交互并读取其输出。

In particular see the section Replacing /bin/sh shell backquote:

特别参见Replacing / bin / sh shell反引号部分:

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

#1


5  

Two parts:

Shell

netstat | python read_netstat.py

Python read_netstat.py

import sys
variable = sys.stdin.read()

That will read the output from netstat into a variable.

这将把netstat的输出读入变量。

#2


6  

It is possible. See:

有可能的。看到:

http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote

In Python 2.4 and above:

在Python 2.4及以上版本中:

from subprocess import *
x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0]

#3


2  

Take a look at the subprocess module. It allows you to start new processes, interact with them, and read their output.

看一下子进程模块。它允许您启动新进程,与它们交互并读取其输出。

In particular see the section Replacing /bin/sh shell backquote:

特别参见Replacing / bin / sh shell反引号部分:

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]