+1 vote
in Python by (160 points)
Within a python script can I call an external command?

2 Answers

+2 votes
by (10.9k points)

@Joy_Lewis ,yes you can call an external command within your python script.Following are the different ways of calling an external command in python-

1. Using the subprocess module

    For new Python versions:

     import subprocess

     subprocess.run(["ls", "-l"])


      For old Python versions:

         import subprocess

         subprocess.call(["ls", "-l"])


2. Os.system(“some_command with args”)

os.system("some_command < input_file | another_command > output_file")  

 3. Using popen class from the subprocess module

print subprocess.Popen(" Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()

 You may also use os.system() method but using subprocess is more advantageous.

According to the official Python document (https://docs.python.org/3/library/os.html#os.system), subprocess module is a much better alternative for os.system()because:

  • Subprocess is more flexible as compared to the system.
  • Subprocess module provides better facilities of spawning a new process and retrieving their results.

Hope this answer will help.

0 votes
by (20.3k points)

Implementation would be like this:

import subprocess

p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in p.stdout.readlines():

    print line,

retval = p.wait()

Now, you can do whatever you want with the stdout data in the pipe. In fact, you can simply delete those parameters (like stdout= and stderr=) and it'll behave like os.system().

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !