w3resource

Python: Run an operating system command using the os module

Python Operating System Services: Exercise-17 with Solution

Write a Python program to run an operating system command using the os module.

Sample Solution:

Python Code :

import os
if os.name =="nt":
   command ="dir"
else:
   command ="ls -l"
os.system(command)

Sample Output:

total 4
-rw-rw-rw- 1 root root 99 Jan 18 10:50 main.py

Python Code Editor:

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

Previous: Write a Python program to write a string to a buffer and retrieve the value written, at the end discard buffer memory.
Next: Write a Python program to start a new process replacing the current process.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Returns the symmetric difference between two iterables, without filtering out duplicate values:

Example:

def tips_symmetric_difference(p, q):
  _p, _q = set(p), set(q)
  return [item for item in p if item not in _q] + [item for item in q if item not in _p]
print(tips_symmetric_difference([2, 4, 6], [2, 4, 8]))

Output:

[6, 8]