In Python’s interactive mode (the Python Shell), you can execute command-line commands using the os and subprocess modules.


🔹 Method 1: Using os.system()

The os.system() function allows you to run command-line commands directly from Python.

Example: Running a Command

import os
os.system("dir")  # Windows (Lists files in current directory)
os.system("ls")   # macOS/Linux

✅ This will execute the command as if you ran it in CMD.

Limitations:

  • It only runs the command but does not return the output.
  • Not ideal for capturing command results.

🔹 Method 2: Using subprocess.run()

The subprocess module provides a more powerful way to execute commands.

Example: Running a Command

import subprocess
subprocess.run(["dir"], shell=True)  # Windows
subprocess.run(["ls"], shell=True)   # macOS/Linux

✅ This method is more secure and recommended.


🔹 Method 3: Capturing Command Output (subprocess.check_output())

To capture the output of a command and use it in Python:

Example: Storing Output in a Variable

output = subprocess.check_output("dir", shell=True, text=True)
print(output)

✅ Now, the command’s output is stored in the output variable.


🔹 Method 4: Running Python Scripts from Interactive Mode

You can also execute Python scripts from interactive mode using:

exec(open("script.py").read())  # Runs a script within interactive mode

or

import subprocess
subprocess.run(["python", "script.py"])

Conclusion

  • Use os.system() for simple command execution.
  • Use subprocess.run() for better control.
  • Use subprocess.check_output() if you need to capture output.

Would you like an example of executing system commands interactively? 😊


Leave a Reply

Your email address will not be published. Required fields are marked *