问题描述
我是Python的新手,我想编写一个Python程序,该程序可以在cmd中执行一些命令并自动从中获取输出。
I am a newbie of Python and I would like to write a Python program that can execute some command in the cmd and get the output from it automatically.
有可能吗?我该怎么做?
Is it possible? How can I do this?
推荐答案
您将要使用:
You will want to use subprocess.Popen
:
>>> import subprocess
>>> r = subprocess.Popen(['ls', '-l']) #List files on a linux system. Equivalent of dir on windows.
>>> output, errs = r.communicate()
>>> print(output)
Total 72
# My file list here
code> Popen -construtor接受参数列表作为第一个参数。该列表以命令开头(在本例中为 ls
),其余值是该命令的开关和其他参数。上面的示例在终端(或命令行或控制台)上写为 ls -l 。相当于Windows的
The
Popen
-construtor accepts a list of arguments as the first parameter. The list starts with the command (in this case ls
) and the rest of the values are switches and other parameters to the command. The above example is written as ls -l
on the terminal (or command line, or console). A windows equivalent would be
>>> r = subprocess.Popen(['dir', '/A'])
这篇关于如何执行命令提示符并从中获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!