如何执行命令提示符并从中获取输出? [英] How to execute command prompt and get the output from it?

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

问题描述

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

有可能吗?我该怎么做?

Is it possible? How can I do this?

推荐答案

您将要使用 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

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆