如何在Python程序中从命令行获取数据?

38 投票
6 回答
51304 浏览
提问于 2025-04-17 06:46

我想在一个Python脚本里运行一个命令行程序,并获取它的输出。

我该怎么做才能把foo显示的信息拿到,以便在我的脚本中使用呢?

比如,我在命令行中输入 foo file1,它会打印出

Size: 3KB
Name: file1.txt
Other stuff: blah

我怎么才能像这样获取文件名:filename = os.system('foo file1')

6 个回答

2

这通常是一个可以在Python中运行的bash脚本的主题:

#!/bin/bash
# vim:ts=4:sw=4

for arg; do
    size=$(du -sh "$arg" | awk '{print $1}')
    date=$(stat -c "%y" "$arg")
    cat<<EOF
Size: $size
Name: ${arg##*/}
Date: $date 
EOF

done

补充说明:如何使用它:打开一个伪终端,然后复制粘贴这个:

cd
wget http://pastie.org/pastes/2900209/download -O info-files.bash

在Python2.4中:

import os
import sys

myvar = ("/bin/bash ~/info-files.bash '{}'").format(sys.argv[1])
myoutput = os.system(myvar) # myoutput variable contains the whole output from the shell
print myoutput
6

通过你的Python脚本调用一个工具并获取输出,最简单的方法就是使用标准库中的 subprocess 模块。你可以看看 subprocess.check_output

>>> subprocess.check_output("echo \"foo\"", shell=True)
'foo\n'

(如果你的工具接收来自不可信来源的输入,记得不要使用 shell=True 这个参数。)

36

使用subprocess模块:

import subprocess

command = ['ls', '-l']
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.IGNORE)
text = p.stdout.read()
retcode = p.wait()

然后你可以对变量text做任何你想做的事情,比如用正则表达式处理、分割等等。

subprocess.Popen的第二个和第三个参数是可选的,可以不写。

撰写回答