我是 Python 的新手,我想编写一个 Python 程序,可以在 cmd 中执行一些命令并自动从中获取输出。
这可能吗?我该怎么做?
最佳答案
您将要使用 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
-构造器接受参数列表作为第一个参数。该列表以命令(在本例中为 ls
)开头,其余值是命令的开关和其他参数。上面的例子在终端(或命令行,或控制台)上写成ls -l
。 Windows 等价物是
>>> r = subprocess.Popen(['dir', '/A'])
关于python - 如何执行命令提示符并从中获取输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24401391/