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

hkl*_*lel 4 python cmd

我是Python的新手,我想编写一个Python程序,该程序可以在cmd中执行一些命令并自动从中获取输出。

可能吗?我怎样才能做到这一点?

msv*_*kon 5

您将要使用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
Run Code Online (Sandbox Code Playgroud)

Popen-construtor接受的参数作为第一个参数列表。该列表以命令开头(在本例中为ls),其余值为该命令的开关和其他参数。上面的示例ls -l在终端(或命令行或控制台)上编写为。Windows等效

>>> r = subprocess.Popen(['dir', '/A'])
Run Code Online (Sandbox Code Playgroud)