我是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
-construtor接受的参数作为第一个参数列表。该列表以命令开头(在本例中为ls
),其余值为该命令的开关和其他参数。上面的示例ls -l
在终端(或命令行或控制台)上编写为。Windows等效
>>> r = subprocess.Popen(['dir', '/A'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句