我知道已经有关于如何在python中使用子进程来运行linux命令的文章,但我只是无法获得正确的语法。请帮帮忙。这是我需要运行的命令..。
/sbin/ifconfig eth1 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}'好的,这就是我现在看到的,语法错误.
import subprocess
self.ip = subprocess.Popen([/sbin/ifconfig eth1 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}'])任何帮助都非常感谢。
发布于 2015-09-22 09:28:05
在此之前已经做过很多次了;但是这里有一个简单的、纯Python的替代方法来替代效率低下的后置处理。
from subprocess import Popen, PIPE
eth1 = subprocess.Popen(['/sbin/ifconfig', 'eth1'], stdout=PIPE)
out, err = eth1.communicate()
for line in out.split('\n'):
line = line.lstrip()
if line.startswith('inet addr:'):
ip = line.split()[1][5:]发布于 2015-09-22 08:48:32
下面是如何用Python构建管道(而不是恢复到Shell=True,因为这更难保护)。
from subprocess import PIPE, Popen
# Do `which` to get correct paths
GREP_PATH = '/usr/bin/grep'
IFCONFIG_PATH = '/usr/bin/ifconfig'
AWK_PATH = '/usr/bin/awk'
awk2 = Popen([AWK_PATH, '{print $1}'], stdin=PIPE)
awk1 = Popen([AWK_PATH, '-F:', '{print $2}'], stdin=PIPE, stdout=awk2.stdin)
grep = Popen([GREP_PATH, 'inet addr'], stdin=PIPE, stdout=awk1.stdin)
ifconfig = Popen([IFCONFIG_PATH, 'eth1'], stdout=grep.stdin)
procs = [ifconfig, grep, awk1, awk2]
for proc in procs:
print(proc)
proc.wait()最好使用re在Python中进行字符串处理。这样做是为了获得ifconfig的标准。
from subprocess import check_output
stdout = check_output(['/usr/bin/ifconfig', 'eth1'])
print(stdout)https://stackoverflow.com/questions/32712129
复制相似问题