Python Command Line Scripting Tutorial – Complete Guide

Have you ever wished to automate certain tasks on your computer or enhance the functionality of your programs? Python command line scripting is the magic wand you need! This powerful feature helps programmers accomplish rather complex tasks swiftly and more effectively.

What is Python Command Line Scripting?

Python command line scripting, also known as shell scripting, is a method of programming Python to automate a series of tasks or actions on the system. This simplified approach to programming involves writing scripts (series of commands) that the command line interpreter can execute.

Python command line scripting is utilized to automate repetitive tasks such as file manipulation or performing system administrative tasks. Developers also use it to extend the functionalities of an application.

Why Should I Learn Python Command Line Scripting?

Learning Python command line scripting has several benefits:

  • Automation: You can use Python command line scripting to automate frequent tasks, thus increasing productivity.
  • Flexibility: Scripts can be customized as per demands making this an extremely dynamic tool for task automation.
  • Improving Programming Skills: With command line scripting, you can attain a deep understanding of Python’s under-the-hood operation and become an expert in debugging and program flow control.

With Python being one of the top-rated programming languages, there’s no better time than now to start learning Python command line scripting.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Writing Your First Python Command Line Script

Before starting, make sure Python is properly installed. Open your terminal and type python --version. If you get an output with the Python version, you’re ready to go.

Let’s write our first simple command line script:

# Use '#' to write comments
print("Hello, Zenva!")

Save the above script as ‘hello.py’ and run it from your command line using python hello.py. You should see ‘Hello, Zenva!’ printed on your console.

Handling Command Line Arguments

Python command line scripts are often used to accept input from users and perform tasks based on the input. To do this, we need to handle command line arguments.

Python’s sys module provides functionalities to do this:

import sys

# Print the name of the script
print(sys.argv[0])

# Print the first command line argument
print(sys.argv[1])

Save the above script as ‘arguments.py’. Running this script with a command line argument (e.g., python arguments.py Zenva) will output the script name and the argument ‘Zenva’.

Performing File Operations

Python command line scripts can be used to automate file operations. The os module provides capabilities for file operations:

import os

# Print current working directory
print(os.getcwd())

This script will print the path of your current working directory when executed in the command line.

Calling Other Scripts

Python command line scripts can call other Python scripts:

import subprocess

# Call another script
subprocess.call("python hello.py", shell=True)

If executed, this script will call ‘hello.py’ script, printing ‘Hello, Zenva!’.

Python command line scripting allows a great deal of system automation and customization. It also serves as a starting point for those looking toward learning further development with Python, such as GUI programming, web development, or data science.

Scripting a Task Scheduler

A practical use of Python command line scripting is to schedule tasks. The sched module lets you achieve this:

import sched, time

# Initialize a scheduler
s = sched.scheduler(time.time, time.sleep)

def task():
    print("Task is running...")

# Schedule the task to run after 5 seconds
s.enter(5, 1, task)

# Run the scheduler
s.run()

This script, when executed, will print ‘Task is running…’ after 5 seconds.

Accessing the Internet

The urllib module allows Python command line scripts to access the internet:

import urllib.request

# Access a webpage
with urllib.request.urlopen('http://www.python.org/') as response:
   html = response.read()
   
print(html)

Running this script will return the source HTML of the Python website.

Reading and Writing Files

Python command line scripting can perform file operations such as reading and writing:

# Write into a file
f = open("file.txt", "w")
f.write("Hello, Zenva!")
f.close()

# Read from a file
f = open("file.txt", "r")
print(f.read())
f.close()

The first part of the code writes ‘Hello, Zenva!’ into ‘file.txt’. The second part reads from ‘file.txt’ and prints its content.

Database Operations

The sqlite3 module allows you to work with a SQLite database:

import sqlite3

# Connect to a SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('database.db')

# Create a cursor
c = conn.cursor()

# Execute SQL commands
c.execute("CREATE TABLE IF NOT EXISTS employees(id integer, name text)")
c.execute("INSERT INTO employees VALUES(1, 'John')")
conn.commit()

# Retrieve data
c.execute("SELECT * FROM employees")
print(c.fetchall())

Running this code creates a SQLite database ‘database.db’, inserts a row into its ’employees’ table, and then fetches and prints all rows from this table.

Where to Go Next

Hopefully, this guide has ignited your interest in Python command line scripting and shown you just how useful and versatile it can be. But where should you go from here?

If you’re starting with Python, or looking to get a broad and comprehensive grasp of Python programming in general, check out our Python Mini-Degree.

The Python Mini-Degree is more than just a course. It’s a collection of interactive lessons, live coding challenges, quizzes and more. You will learn to build real projects like arcade games, medical diagnosis bots, and to-do list apps. It’s designed to cater to beginners as well as experienced programmers looking to solidify their Python skills.

What sets our Python Mini-Degree apart is the flexibility it offers. You have the freedom to learn at your own pace and the content is regularly updated to keep up with the latest industry practices and technology. You’ll also have access to expert mentors and receive a certificate upon completion. With a course curriculum certified by reputed organizations, the Python skills you’ll gain can lead to exciting job opportunities.

Additionally, for a wider collection of our offerings in Python, you can explore our Python courses.

Conclusion

As our journey through Python command line scripting comes to an end, remember that this is just the tip of the iceberg. Python is a vast and powerful language, and at Zenva, we strive to guide you through this exciting landscape of opportunities. With meaningful courses crafted by industry experts, we aim to equip you with in-demand skills that will take your programming journey to new heights.

Want to continue your Python learning voyage? Our Python Mini-Degree serves as an extensive guide catering to both beginners and experienced programmers. It’s time for you to grasp the power of Python and transform your coding dreams into reality.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.