Python · January 17, 2024

Run Python Script from Terminal or CMD

So you’ve dipped your toes into the Python pool, and you’re ready to dive deeper. But navigating the terminal or command prompt (CMD) can seem like venturing into uncharted territory. Fear not, intrepid Pythonista! This post is your map to running Python scripts with confidence, complete with SEO-friendly tips to make your knowledge shine.

Why Go Terminal?

Sure, graphical interfaces offer comfort, but the terminal unlocks Python’s true potential. It’s your gateway to:

  • Scripting Power: Automate repetitive tasks and build complex workflows with ease.
  • Direct Control: Fine-tune script execution with advanced arguments and environment variables.
  • Server Access: Unleash the power of remote servers and cloud deployments.
  • Debugging Prowess: Isolate and fix errors efficiently with precise command-line feedback.

Gearing Up:

Before we set sail, ensure you have these essentials:

  1. Python Installed: Get the latest version for your system from https://www.python.org/downloads/.
  2. Terminal/CMD Access: Windows users, hit Win + R and type cmd. Mac/Linux users, open Terminal from your utilities folder.
  3. Basic Navigation: Learn basic commands like cd (change directory), ls (list files), and pwd (show current directory).

Setting Sail:

Now, let’s navigate the Python seas!

  1. Navigating to Your Script: Use cd to reach the directory containing your Python script (e.g., cd C:\MyScripts).
  2. Running the Script:
    • Simply type python followed by your script name (e.g., python myscript.py). Hit Enter, and watch your script come to life!
    • You can run the script without navigation as well e.g., python C:\MyScripts\myscript.py
    • We can run the code using python -m myscript or python -m MyScripts.myscript
      • Note: To run the script with -m option C: or E: directory path will not work. You need to at least cd to C: or E: or D: and from there you can use above code to run the script.
  3. Passing Arguments: Want to fine-tune your script? Use arguments after the script name (e.g., python myscript.py arg1 arg2).

Get it in action here.