向列表添加子进程似乎只是在python中添加子进程对象的位置



在控制台中使用以下命令打印wlan0网卡的本地MAC地址。我想将其集成到一个脚本中,其中列表的第0个子列表将用exer

中的本地MAC填充
ifconfig wlan0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

正在使用的列表,本地化,从称为扫描的字典中获取它的第一个和第二个子列表。

所以我想在第0个子列表中有本地MAC,并且在第1和第2个子列表中每个条目都有一个条目。我已经试过代码:

for s in scanned:
    localisation[0].append(subprocess.Popen("ifconfig wlan0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'", shell=True))

但是我只得到

<subprocess.Popen object at 0x2bf0f50>

对于列表中的每个条目。尽管有正确数量的条目

我还有一个问题,由于某种原因,程序将代码输出打印到屏幕上,这是我不希望发生的。

我做错了什么?

这是我的尝试:

use check_output给出该命令的输出。

In [3]: import subprocess
In [4]: subprocess.check_output("ip link show wlan0 | grep link | awk '{print $2}'",shell=True).strip()
Out[4]: '48:5d:60:80:e5:5f'

使用ip link show代替ifconfig为您保存sudo命令

popen对象在某种意义上是一个文件对象。

from subprocess import *
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
handle.stdin.write('echo "Heeey there"')
print handle.stdout.read()
handle.flush()

不为您重定向所有输出的原因是stderr=PIPE,否则无论如何都会回显到控制台。重定向到PIPE是个好主意。

此外,使用shell=True通常是一个坏主意,除非你知道为什么你需要它。在这种情况下(我认为)你不需要它。

aaa最后,您需要将您想要执行的命令划分为一个列表,至少包含2个项目或更多。例子:

c = ['ssh', '-t', 'user@host', "service --status-all"]

通常是ssh -t user@root "service --status-all",请注意"service --status-all"的NOT拆分部分,因为在我的示例中,这是作为一个整体发送到SSH客户端的参数。

不尝试,尝试:

c = ["ifconfig", "wlan0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'"]

甚至:

from uuid import getnode as get_mac
mac = get_mac()

只调用Popen只返回一个新的Popen实例:

In [54]: from subprocess import Popen,PIPE
In [55]: from shlex import split   #use shlex.split() to split the string into correct args
In [57]: ifconf=Popen(split("ifconfig wlan0"),stdout=PIPE)
In [59]: grep=Popen(split("grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'"),
                                                   stdin=ifconf.stdout,stdout=PIPE)
In [60]: grep.communicate()[0]
Out[60]: '00:29:5e:3b:cc:8an'

使用communicate()从特定Popen实例的stdinstderr中读取数据:

In [64]: grep.communicate?
Type:       instancemethod
String Form:<bound method Popen.communicate of <subprocess.Popen object at 0x8c693ac>>
File:       /usr/lib/python2.7/subprocess.py
Definition: grep.communicate(self, input=None)
Docstring:
Interact with process: Send data to stdin.  Read data from
stdout and stderr, until end-of-file is reached.  Wait for
process to terminate.  The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr).

最新更新