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.major < 3 and sys.version_info.minor < 3:
sys.exit("Python 3.3 or higher is required; you're running version " +
str(sys.version_info.major) + "." + str(sys.version_info.minor))
Command Line Arguments
With the sys module
The sys module provides system-specific parameters and functions
import sys
print("{0} CLI parameters: {1} ".format(str(len(sys.argv)), sys.argv))
print("1st parameter: {0}".format(sys.argv[0])) # Always the path to actual script.
if (len(sys.argv) >= 2): print("2nd parameter: {0}".format(sys.argv[1]))
if (len(sys.argv) >= 3): print("3rd parameter: {0}".format(sys.argv[2]))
Result:
> .\test.py foo "bar baz"
3 CLI parameters: ['C:\\devel\\_test\\test.py', 'foo', 'bar baz']
1st parameter: C:\devel\_test\test.py
2nd parameter: foo
3rd parameter: bar baz
With the argparse module
The argparse module comes with Python 2.7 and 3.2 and is the recommended command-line parsing module in the Python standard library:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--param', dest='ParameterX', type=str, help='Defines X')
parser.add_argument('--keep_build', action='store_true')
args = parser.parse_args()
print (args.ParameterX)
if (args.keep_build): print("Keep the build directory")
else : print("Delete the build director")
Result:
> .\test.py --param foo
foo
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)
Film & Television (56)
How To (68)
Journal (18)
Miscellaneous (4)
News & Announcements (21)
On Software (12)
Projects (26)