w3resource

Python: Call an external command in Python

Python Basic: Exercise-45 with Solution

Write a python program to call an external command in Python.

Sample Solution-1:

Python Code:

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

Sample Output:

drwxrwxr-x 2 students  students    4096 Sep 15  2016 c48d5200-7b43-11e6-b7e4-2516b8e1f7f8                     
drwxrwxr-x 2 students  students    4096 Sep 21  2016 c4a96850-7fdf-11e6-a2b3-172481646809                     
drwxrwxr-x 2 students  students    4096 Sep  7  2016 c4d98410-74de-11e6-ac36-65f2f75d0c7b                     
drwxrwxr-x 2 students  students    4096 Sep  6  2016 c4fa6e10-7424-11e6-812c-5574d751e2d7                     
drwxrwxr-x 2 prashanta prashanta   4096 Feb 20 18:24 c5216400-f76b-11e6-8ad1-9b7f6e755728   
-------
-rw-rw-r-- 1 students  students      27 Sep 28  2016 temp.txt                                                 
-rw-rw-r-- 1 students  students      27 Sep 28  2016 test.txt  

Sample Solution-2:

Python Code:

import os
print(os.system('ls -l'))

Sample Output:

total 4
-rw-rw-rw- 1 root root 36 Jun  9 10:47 main.py
0 

Sample Solution-3:

Python Code:

import psutil
 print(psutil.cpu_count())

Sample Output:

4

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to locate Python site-packages.
Next: Write a python program to get the path and name of the file that is currently executing.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Unpack variables from iterable:

# One can unpack all iterables (tuples, list etc)
>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)

>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)