4

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?

5
  • Do you mean get input form the command line interactively ? Commented Jun 25, 2014 at 6:13
  • The question seems a little vague to me. Do you want to pass arguments through cmdline to get a result? Or is it just compiling the code "python blah.py" for example? Commented Jun 25, 2014 at 6:13
  • I interpret this so that the op wants to call something from the command line. Like a subprocess. Commented Jun 25, 2014 at 6:14
  • Oh, I mean input text to the cmd and get the result from it Commented Jun 25, 2014 at 6:18
  • This might help: docs.python.org/2/library/subprocess.html But I'm unsure of what you are asking so maybe not. Commented Jun 25, 2014 at 6:20

2 Answers 2

5

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

you mean how to excute some command from cmd use

import os

os.system(a string);

1 Comment

Please avoid os.system(). It's deprecated and the official way is to use subprocess. It says this on the documentation of the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.