本文介绍了Python ---如何执行命令提示符并从中获取输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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.

有可能吗?

推荐答案

您将要使用:

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



Popen -construtor接受一个参数列表作为第一个参数。该列表以命令开头(在这种情况下 ls ),其余的值是命令的开关和其他参数。上述示例在终端(或命令行或控制台)上以 ls -l 编写。

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'])

这篇关于Python ---如何执行命令提示符并从中获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 11:07
查看更多