如何从Python程序中的命令行获取数据? [英] How to get data from command line from within a Python program?

查看:183
本文介绍了如何从Python程序中的命令行获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从python脚本中运行命令行程序并获取输出。



如何获取foo显示的信息,可以在我的脚本中使用它吗?



例如,我从命令行调用 foo file1 ,并打印出

 大小:3KB 
名称:file1.txt
其他材料:blah
pre>

如何获取文件名做 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 out

Size: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆