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,320 points
31 views

2 answers to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,710 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
• 66,910 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,140 points
77 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
• 10,860 points
10 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
96 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
56 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,710 points
1,069 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,710 points
51 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.