Calling an external command in Python

0 votes

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?

Oct 11, 2018 in Python by ariaholic
• 7,340 points
40 views

2 answers to this question.

0 votes

Look at the subprocess module in the standard library:

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

The advantage of subprocess vs. system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...).

The official documentation recommends the subprocess module over the alternative os.system():

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function [os.system()].

The "Replacing Older Functions with the subprocess Module" section in the subprocessdocumentation may have some helpful recipes.

Official documentation on the subprocess module:

answered Oct 11, 2018 by charlie_brown
• 7,720 points
0 votes
import os

os.system('external_command')

Replace external_command in the above code with the command you want to execute.

answered Oct 16, 2018 by Omkar
• 67,540 points

Related Questions In Python

0 votes
1 answer

'python' is not recognized as an internal or external command

I have met same issue when I ...READ MORE

answered Aug 24, 2018 in Python by Priyaj
• 56,540 points
109 views
0 votes
1 answer

External command in Python

you can check the subprocess module in ...READ MORE

answered Oct 1, 2018 in Python by SDeb
• 13,160 points
20 views
+4 votes
7 answers
+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
679 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 240 views
+4 votes
6 answers
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,720 points
1,723 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
74 views