Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Python: Call an external command

Python Basic: Exercise-45 with Solution

Write a Python program to call an external command.

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 Programming skills with w3resource's quiz.



Python: Tips of the Day

Find current directory and file's directory:

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
  • os.path.dirname(path) (returns "the directory name of pathname path")
  • os.getcwd() (returns "a string representing the current working directory")
  • os.chdir(path) ("change the current working directory to path")

Ref: https://bit.ly/3fy0R6m