Python Code Snippets

Below are some useful Python code snippets for use in everyday projects.

If a Python script is run from the command line, arguments can be specified that can be used within the script being called.

python demo.py George 30

These arguments can be used in the script as follows.

import sys

name = sys.argv[1]
age = sys.argv[2]

print(f"{name} is {age} years old.")

Sometimes it may be necessary to accept input from the user so that it can be utilised within a script. This can be achieved using the 'input' function. Here, the input is placed into a variable called 'user' and then displayed as part of a greeting.

# Greeting variable.
greeting = "Hello"

# Accept user input.
user = input("Please enter your name: ")

# Display greeting.
print(f"{greeting} {user}!")

When dealing with directories and files it may be necessary to check for their existence. Below is an example of how to do this.

import os

# Example path and file.
exampletPath = 'C:\\demo\\'
exampleFile = 'example.txt'

# Check if the path exists.
if os.path.exists(exampletPath):

    print(f"The path '{exampletPath}' exists.")

else

    print(f"The path '{exampletPath}' doesn't exists.")

# Check if the file exists.
if os.path.isfile(exampleFile):

    print(f"The file '{exampletPath}{exampleFile}' exists.")

else

    print(f"The file '{exampletPath}{exampleFile}' doesn't exists.")

Python can be used to copy and move files.

import shutil

# Example paths and files.
exampletPathSource = 'C:\\demo\\'
exampletPathDestination = 'C:\\demo\\backup\\'
exampleFile1 = 'example1.txt'
exampleFile2 = 'example2.txt'

# Copy the example1.txt file.
shutil.copyfile(exampletPathSource + exampleFile1, exampletPathDestination + exampleFile1)

# Move the example2.txt file.
shutil.move(exampletPathSource + exampleFile2, exampletPathDestination + exampleFile2)

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

import random

# Minimum and maximum values for random number.
min_val = 1
max_val = 59

# Generate random number.
random_number = random.randint(min_val, max_val)

# Display the number in the console/terminal.
print(random_number)

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

import random

# Possible characters in password.
alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
numbers = '0123456789'
nonAlpha = '{]+-[*=@:)}$^%;(_!&#?>/|.'

# Combine possible password characters into one string.
charSet = alpha + numbers + nonAlpha

# Minimum and maximum password length.
minLength = 20
maxLength = 30

# Select a random password length between the minimum and maximum.
length = random.randint(minLength, maxLength)

# Variable for new password.
result = ""

# Construct new password.
for num in range(0, length):

    # Add a randomly selected character to the new password.
    result += charSet[random.randint(0, len(charSet)-1)]

# Display the password.
print(result)

The 'platform' module can be used to access certain information relating to the computer that a program is running on. Below is an example of some of the information that is available.

import platform

print(f"System Type: {platform.machine()}")
print(f"Computer Name: {platform.node()}")
print(f"Operating System: {platform.platform()}")
print(f"Processor: {platform.processor()}")
print(f"System Release Version: {platform.release()}")
print(f"Python Version: {platform.python_version()}")
print(f"Python Compiler: {platform.python_compiler()}")

When handling a number of files, it can sometimes be useful to compress them in to one file. Python can be used to both create and extract from a zip archive.

import shutil

# Example paths and files.
exampletPathSource = 'C:\\demo\\'
exampletPathDestination = 'C:\\demo2\\'
examplePathZip = 'C:\\temp\\demo'  # Exclude extension from file name.
exampleFileFormat = 'zip'

# Create the zip archive file.
shutil.make_archive(examplePathZip, exampleFileFormat, exampletPathSource)

# Extract the zip archive file.
shutil.unpack_archive(f"{examplePathZip}.{exampleFileFormat}",
                      exampletPathDestination, exampleFileFormat)

The 'socket' module, which is part of the 'Standard Library', can be used to find out IP address and domain information. A domain name can be used to find out its IP address, and similarly, an IP address can be used to find out its domain name.

import socket

# Find IP address of specified hostname.
hostname = "example.com"

try:

    # Try to retrieve the IP address and display it.
    hostnameip = socket.gethostbyname(hostname)
    print(f"The IP address for {hostname} is: {hostnameip}")

except socket.herror:

    print(f"No IP address found for the hostname: {hostname}")

# Find hostname of specified IP address.
ipaddress = "8.8.8.8"

try:

    # Try to retrieve the hostname and display it.
    iphostname = socket.gethostbyaddr(ipaddress)
    print(f"The hostname for {ipaddress} is: {iphostname[0]}")

except socket.herror:

    print(f"No hostname found for the IP address: {ipaddress}")

Whois is a utility that provides publicly available information about a domain or IP address. This example requires the installation of the 'python-whois' module and obtains information for the 'example.com' domain, then displays it. The information is returned in a dictionary.

import whois # From: python-whois

# Return a dictionary of Whois information.
whois_info = whois.whois("example.com")

# Display individual items from the dictionary of information returned.
print(f"Domain Name: {whois_info['domain_name']}")
print(f"Registrar: {whois_info['registrar']}")
print(f"Whois Server: {whois_info['whois_server']}")
print(f"Referral URL: {whois_info['referral_url']}")
print(f"Updated Date: {whois_info['updated_date']}")
print(f"Creation Date: {whois_info['creation_date']}")
print(f"Expiration Date: {whois_info['expiration_date']}")
print(f"Name Servers: {whois_info['name_servers']}")
print(f"Status: {whois_info['status']}")
print(f"Email Address: {whois_info['emails']}")
print(f"DNSSEC: {whois_info['dnssec']}")
print(f"Name: {whois_info['name']}")
print(f"Organisation: {whois_info['org']}")
print(f"Address: {whois_info['address']}")
print(f"City: {whois_info['city']}")
print(f"State: {whois_info['state']}")
print(f"Registrant Postal Code: {whois_info['registrant_postal_code']}")
print(f"Country: {whois_info['country']}")

A text file can be read from and processed line by line.

# Open file for reading.
fileToRead = open('C:\\demo\\demo.txt', 'r')

# Assign the file contents to a variable.
lines = fileToRead.readlines()

# Process the file contents line by line.
for line in lines:

    # Display the line in the console/terminal,
    # with the new line character removed.
    print(line.strip())