且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python ---如何执行命令提示符并从中获取输出?

更新时间:2023-11-11 21:38:52

您将要使用 subprocess.Popen

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