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 aryya
• 7,370 points
120 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,780 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
• 69,040 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
• 57,550 points
234 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,250 points
60 views
0 votes
1 answer

How to call an external command from Python?

Hi@akhtar, You can use the os module in ...READ MORE

answered Jun 24 in Python by MD
• 41,020 points
30 views
+4 votes
7 answers
+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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,183 views
0 votes
0 answers
+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,780 points
5,551 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,780 points
273 views