Miscellaneous Python

Python command line arguments:

Here is sys.argv demonstrated with a silly script that repeats your message back in all caps and adds exclamation points at the end:

shout.py:

import sys

if len(sys.argv) > 2 and sys.argv[1] == “say”:

counter = 0

for arg in sys.argv:

if counter >= 2:

print(str(arg).upper(), end=””)

if counter < (len(sys.argv) – 1):

print(” “, end=””)

counter += 1

print(“!!!”)

elif len(sys.argv) > 1 and sys.argv[1] == “greet”:

print(“HELLO THERE!”)

else:

print(“AAAAAAAA”)

How to run it:

Go to the directory you saved it in, and then type either python shout.py or python3 shout.py (it depends on your OS and your path variable):

PS C:\Users\Alan\Desktop\bookPython> python shout.py say this weather is really amazing

THIS WEATHER IS REALLY AMAZING!!!

Other uses:

PS C:\Users\Alan\Desktop\bookPython> python shout.py

AAAAAAAA

PS C:\Users\Alan\Desktop\bookPython> python shout.py greet

HELLO THERE!

The above is output from a PowerShell window, though you can also use Terminal, Git Bash, and so on.

Instead of getting user input through something like the input() function, you can make it so that your program gets run based on the command line arguments that are provided to it. This can make your program very useful, and if a program can be used with command line arguments, you can actually write another program to control that program. It’d be harder to make a program that enters input in for the input() function.

Python getopt:

The official Python documentation at python.org describes getopt as a module that “helps scripts to parse the command line arguments in sys.argv.” It’s called get opts because command line arguments for a program are sometimes called options, or opts for short. To easily parse them, you want something that can help you get them, hence getopt.

I’ve parsed sys.argv command line arguments manually in the past, but it’s more of a pain than if you use getopt.

In order to use getopt, your python script must first import it with import getopt.

Command line arguments typically start with either one or two dashes.

Here is an example:

./myprogram.py –help

./myprogram.py -h

Two dashes indicate the fuller name of the option, whereas one is usually associated with the abbreviated/shorthand version. In the above example, –help and -h do the same thing. You could technically make them do different things, but this is a common convention for command line programs.

Options can also have values, such as ping -c 4 google.com, which means use the count (-c) option with a value of 4, in order to ping google.com 4 times. This is the Unix-like ping command, not the Windows one.

sys.argv is an array of arguments, and the zeroth argument to a program is itself, so you can disregard it when trying to get user input in the form of command line arguments. The way to get the first element through the last in the sys.argv array is to use this:

sys.argv[1:]

That will get all command line args except for sys.argv[0].

Let’s make a simple program that calculates the area of a box in order to make it easy to understand how getopt works. The box has length, height, and width. The area is just all three of them combined. The program will get all of these from the command line arguments.

import sys

import getopt

length = 0

height = 0

width = 0

opts, args = getopt.getopt(sys.argv[1:], “l:h:w:”)

for opt, arg in opts:

if opt == “-l”:

length = arg

elif opt == “-h”:

height = arg

elif opt == “-w”:

width = arg

else:

print(“incorrect option entered”)

area = int(length) * int(width) * int(height)

if (area != 0):

print(“The area of the box is ” + str(area))

else:

print(“missing args”)

In the above example, you can run the program like this:

$ python getopts.py -h 23 -w 12 -l 67

The area of the box is 18492

The command line opts can be written in any order, such as height first, width second, or length third, or any other order too. This is more flexible than manual methods of parsing sys.argv stuff.

The above code isn’t perfect, but it shows how you can easily parse opts and args.

In case you’re confused, in the above example, -h, -w, and -l are opts. And 23, 12, and 67 are args. Technically, they’re all args in sys.argv, but for getopt, there is a distinction between opt and arg.

Python GUI options:

If you want to make a graphical program in Python, use tkinter. It comes with Python by default.

Here is a very quick (and bad) example of how to make a graphical Python program using tkinter:

#!/usr/bin/env python3

import sys

import tkinter

from tkinter import Label

clicks = 0

appwindow = tkinter.Tk(className=”My cool app”)

clickLabel = Label(appwindow, text=str(clicks))

def clicker():

global clickLabel

global clicks

clicks += 1

clickLabel.forget()

clickLabel = Label(appwindow, text=str(clicks))

clickLabel.pack()

def main():

print(“hello”)

button = tkinter.Button(appwindow, text=’Click me’, command=clicker)

button.pack()

clickLabel.pack()

appwindow.mainloop()

if __name__ == ‘__main__’:

try:

main()

except KeyboardInterrupt:

print(“\nQuitting. Goodbye.”)

sys.exit()

The above is a simple “clicker” app which has a button to increment a click counter. The window only shows the button and number of times the button has been clicked. This is just a simple demonstration of how you can make a graphical program. It’s not intended to be a serious program. Many of the code examples in this book are mainly for demonstrating features of programming.

Python sleep:

import time

chars = list(“software development”)

for char in chars:

print(char)

time.sleep(0.5)

Python subprocess module:

When you run a program, it creates a process. If you want to break up your program so it can run on multiple cores, you can use threads. But programs can also spawn other processes. If you want to run a program from within another program, you have to use the subprocess module.

Here is a subprocess example that uses a shell command called touch to make a new file called hello.txt:

import subprocess

subprocess.run([“touch”, “hello.txt”])

The command line program called touch creates new blank files (at least if you’re using a Unix-like shell such as bash and/or have MinGW installed). The argument for it is hello.txt, which is a separate element in the array passed to the run() method.

If you want to run bash commands from within a python program, or even just run other programs you have, you need to use the subprocess module. Some people say it’s a bad practice to do things this way, but you might find use in it here and there.

Check out the official python documentation for more information about the subprocess module:

https://docs.python.org/3/library/subprocess.html

Python upper() and lower():

altCaps = “tHiS iS sIlLy”

print(altCaps.lower())

lowerCaseStr = “from lower to upper”

print(lowerCaseStr.upper())

Python len():

def main():

stringExample = “here are some words”

print(len(stringExample))

Congratulations on completing section 5!

You can now tell people that you’re a Python developer! You can go and make lots of cool stuff now!

← Previous | Next →

Python Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *