Python Snippets

A collection of code snippets, small pearls of wisdom and bits of knowledge, that may come handy at times.

Don’t expect well thought out descriptions or highly structured content here; these are snippets.
(But there are some links spread around for further reading.)

You can also find some more practical functions in the Python area of my “misc_public” Git repository on BitBucket.org.


Don’t call your own module “test.py”

A file “test.py” that acts as a stand-alone script is fine, but a file with that name that should act as a module (i.e. to be imported by others) is problematic.

Example:

Module: X:\MyModules\test.py

def foo (i):
    print(i)

Script: X:\MyScripts\script1.py

sys.path.append('X:\\MyModules' )
import test

test.foo('bar')

That will produce this error message:

AttributeError: module 'test' has no attribute 'foo'

A check with help(test) will show you that Python’s own Regression tests package for Python will be used, not yours…


Check whether a certain version on Python is used

… exit if not:

import sys

if sys.version_info[0] < 3:
	sys.exit("Sorry, you need Python 3 or higher for this script.\nYou seem to be running an older version of Python:\n" + sys.version)
if sys.version_info.major < 3 and sys.version_info.minor < 3:
	sys.exit("Sorry, you need Python 3.3 or higher for this script.\nYou seem to be running an older version of Python:\n" + sys.version)

Ask the user for input on the command line

Will also open a command prompt window when started from the GUI/file explorer.

import sys

in_var = input("Enter a value: ")

if int(in_var) < 10:
	print("%s is less than 10" % in_var)
else:
	print("%s is equal to or more than 10" % in_var)

# Wait for ENTER. Needed to keep the cmd window open on Windows when started from GUI/with double-click.
input("Press Enter to exit...")

Running code as a script or importing code as a module (in another script).

mymodulescript.py

def func (i):
    print(i)

func("This runs whether its imported or run as a script.")

if __name__ == '__main__':
	func("This part runs only if the file is called directly (as a script).")

Format (raw) strings

Reminder: r'...' (or r"..." or R'...' or R"...") will generate raw (literal, unescaped, unmodified) text strings.

But one can still use the usual formatting helper with those:

command  = "Command foo"
argument = "-argument bar"

cli_string1 = r'{0} {1}'.format(command, argument)
cli_string2 = fr'{command} {argument}'

print(cli_string1)
print(cli_string2)