How to run external command in Python?

Hi,

I am writing an application in Python and there is requirement of calling the external command from the Python program. I spend some time but could not find good example of calling external command.

How to run external command in Python?

Thanks

View Answers

May 13, 2017 at 7:36 PM

Hi,

In Python you have to use the sub-process. The subprocess module is very useful and provides many functionality.

I allows the developer to write program which can spawn a new processes and connect with main process with input/output/error pipes.

You can to use the sub process to achieve this.

For example following code:

from subprocess import call
call(["ls", "-l"])

Above command calls the external ls -l Linux command. This way you can easily call external program /command from Python main program.

Thanks









Related Tutorials/Questions & Answers:
Advertisements