Python --- How to execute a command line and get output from it?

I am new to Python and I would like to write a Python program that can execute some command in cmd and automatically get output from it.

Is it possible? How can i do this?

Thanks, advanced!

+4
source share
2 answers

Do you 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

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 the keys and other parameters of the command. The above example is written as ls -lon the terminal (either on the command line or in the console). Windows equivalent would be

>>> r = subprocess.Popen(['dir', '/A'])
+4

, cmd

import os

os.system();

0

Source: https://habr.com/ru/post/1545939/


All Articles