如何从Python程序中的命令行获取数据? [英] How to get data from command line from within a Python program?
问题描述
我想从python脚本中运行命令行程序并获取输出。
如何获取foo显示的信息,可以在我的脚本中使用它吗?
例如,我从命令行调用 foo file1
,并打印出
大小:3KB
pre>
名称:file1.txt
其他材料:blah
如何获取文件名做
filename = os.system('foo file1')
?解决方案使用子过程模块:
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
的第三个参数是可选的,可以删除。I want to run a command line program from within a python script and get the output.
How do I get the information that is displayed by foo so that I can use it in my script?
For example, I call
foo file1
from the command line and it prints outSize: 3KB Name: file1.txt Other stuff: blah
How can I get the file name doing something like
filename = os.system('foo file1')
?解决方案Use the subprocess module:
import subprocess command = ['ls', '-l'] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.IGNORE) text = p.stdout.read() retcode = p.wait()
Then you can do whatever you want with variable
text
: regular expression, splitting, etc.The 2nd and 3rd parameters of
subprocess.Popen
are optional and can be removed.这篇关于如何从Python程序中的命令行获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!