How to Run Python Script from Command Line Easily
To run a Python script from the command line, open your terminal or command prompt and type
python script_name.py where script_name.py is your file. Press Enter, and the script will execute showing any output in the terminal.Syntax
The basic syntax to run a Python script from the command line is:
python: This calls the Python interpreter.script_name.py: This is the name of your Python file.
You can also use python3 if your system has both Python 2 and 3 installed.
bash
python script_name.py
Example
This example shows a simple Python script that prints a greeting. Running it from the command line will display the message.
python
print("Hello from Python script!")
Output
Hello from Python script!
Common Pitfalls
Common mistakes include:
- Not being in the correct folder where the script is saved.
- Using
pythonwhen your system requirespython3. - File name typos or missing the
.pyextension.
Always check your current directory with pwd (Mac/Linux) or cd (Windows) and navigate to the script folder before running.
bash
Wrong: python myscript Right: python myscript.py
Quick Reference
Tips to run Python scripts smoothly:
- Use
python3ifpythonruns Python 2. - Navigate to the script folder using
cdbefore running. - Make sure the script file ends with
.py. - Use
python script.py arg1 arg2to pass arguments.
Key Takeaways
Use
python script_name.py in the terminal to run your Python script.Make sure you are in the folder where the script is saved before running it.
Use
python3 if your system defaults python to version 2.Check your script file name and extension carefully to avoid errors.
You can pass arguments after the script name if your script accepts them.