Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
podcast
Filter by Categories
ArcGIS Pro
GDAL
GeoJson
Map
Python
QGIS
Uncategorized

How To Run Python Scripts From Command Line

Mastering Python Scripts: From Command Line Execution to Argument Passing

In this blog post, we’ll guide you through the process of running Python scripts from the command line, starting from verifying your Python installation to writing and executing your first script. We’ll then delve into the powerful concept of passing arguments to your scripts, explaining why you might want to do this and how it can make your scripts more versatile and reusable.

By the end of this post, you’ll have a solid understanding of how to run Python scripts from the command line and the benefits of passing arguments to your scripts. Whether you’re looking to automate tasks, test and debug your code more efficiently, or integrate your scripts into larger systems, these skills will prove invaluable. So, let’s get started on this exciting journey into the depths of Python scripting!

Here are some Python libraries you might be interested in!

Here’s a step-by-step guide on how to run Python scripts from your command line or terminal

Step 1: Verify Python Installation

First, you need to ensure that Python is installed on your system. Open your command line or terminal and type:

python --version

This command should return the version of Python installed on your system. If Python is not installed, you will need to download and install it from the official Python website.

Step 2: Write a Python Script
Next, you need a Python script to run. You can create a new Python file (with a .py extension) using a text editor. For example, let’s create a simple script that prints “Hello, World!”. Save this script as hello.py.

print("Hello, World!")

Step 3: Navigate to the Script’s Directory
In the command line or terminal, navigate to the directory where you saved your Python script using the cd (change directory) command. For example, if you saved hello.py in a directory called scripts on your desktop, you would navigate to it like this:

cd Desktop/scripts

Step 4: Run the Python Script
Now that you’re in the same directory as your Python script, you can run the script using the python command followed by the script’s name:

python hello.py

This command tells Python to execute the code in the hello.py file. You should see the text “Hello, World!” printed to your command line or terminal.

Note: If you have both Python 2 and Python 3 installed on your system, you might need to use python3 instead of python to run Python 3 scripts.

And that’s it! You’ve successfully run a Python script from the command line or terminal.

Want to pass arguments to your Python script?

Passing arguments to a Python script from the command line can be very useful in a variety of scenarios:

  1. Flexibility: It allows you to write flexible scripts that can perform different tasks depending on the arguments provided. For example, you could write a script that processes data, and by passing different file names as arguments, you can use the same script to process different data files.
  2. Automation: It’s essential for automation and scheduling tasks. If you want to run your script automatically at certain times using tools like cron (on Unix-based systems) or Task Scheduler (on Windows), you’ll often need to pass arguments to specify details of the task.
  3. Testing and Debugging: It can be useful for testing and debugging, as you can easily change the inputs to your script without having to modify the script itself.
  4. Code Reusability: It promotes code reusability. Instead of having multiple similar scripts for different inputs, you can have one script that takes various inputs as arguments.
  5. Integration with Other Programs: It’s also necessary when your script is part of a larger system, and other programs or scripts call your script with specific arguments.

How to pass arguments to your Python script

To pass arguments to your Python script from the command line, you can use the built-in sys module or the argparse module for more complex requirements. Here’s a basic guide for both:

Using sys.argv

sys.argv is a list in Python, which contains the command-line arguments passed to the script. The first item in this list, sys.argv[0], is always the name of the script itself. The arguments follow the script name.

Here’s an example of a script that accepts arguments using sys.argv:

import sys

print("Script Name:", sys.argv[0])
print("First argument:", sys.argv[1])
print("Second argument:", sys.argv[2])

You can run this script from the command line and pass arguments like so:

python script.py arg1 arg2

Using argparse

argparse is a more sophisticated module that allows you to specify the number of arguments, default values, data types, help messages, and more. Here’s an example:

import argparse

parser = argparse.ArgumentParser(description="This is our description")
parser.add_argument("arg1", help="This is the first argument")
parser.add_argument("arg2", help="This is the second argument")

args = parser.parse_args()

print("arg1:", args.arg1)
print("arg2:", args.arg2)

You can run this script from the command line and pass arguments like so:

python script.py value1 value2

In this case, argparse also automatically generates help and usage messages and issues errors when users give the program invalid arguments. You can see the help message by running:

python script.py -h

These are basic examples. Both sys.argv and argparse can handle more complex scenarios as needed.

FAQ’s

How do I know if Python is installed on my system?

You can check this by typing python --version or python3 --version in your command line or terminal. This should return the version of Python installed on your system.

What if I have multiple versions of Python installed on my system?

If you have both Python 2 and Python 3 installed, you might need to use python3 instead of python to run Python 3 scripts.

What if my Python script is in a different directory?

You can navigate to the directory containing your script using the cd (change directory) command in the terminal before running the script.

How can I pass arguments to my Python script from the command line?

You can pass arguments directly after the script name. Inside the script, you can access these arguments using the sys.argv list or the argparse module for more complex scenarios.

What if I get an error saying ‘python’ is not recognized as an internal or external command?

This usually means that Python is not installed or the Python executable is not in your system’s PATH. You might need to add Python to your PATH during installation or manually add it later.

Can I run a Python script without typing ‘python’ before the script name?

Yes, but it requires additional steps. On Unix-based systems, you can add a shebang (#!/usr/bin/env python3) at the top of your script and make the script executable using the chmod +x script.py command. On Windows, you can associate the .py extension with the Python interpreter.

How can I handle errors in my Python script when running it from the command line?

Python will print any errors to the terminal by default. You can use Python’s built-in error handling mechanisms, such as try/except blocks, to handle errors more gracefully.

About the Author
I'm Daniel O'Donohue, the voice and creator behind The MapScaping Podcast ( A podcast for the geospatial community ). With a professional background as a geospatial specialist, I've spent years harnessing the power of spatial to unravel the complexities of our world, one layer at a time.