hklel
hklel

Reputation: 1634

How to execute command prompt and get the output from it?

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?

Upvotes: 4

Views: 505

Answers (2)

msvalkon
msvalkon

Reputation: 12077

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

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

Upvotes: 5

user3771709
user3771709

Reputation: 49

you mean how to excute some command from cmd use

import os

os.system(a string);

Upvotes: 0

Related Questions