Skip to content

Instantly share code, notes, and snippets.

@fragmuffin
Last active May 16, 2024 00:53
Show Gist options
  • Save fragmuffin/d2332557a09ec437765254635493e63f to your computer and use it in GitHub Desktop.
Save fragmuffin/d2332557a09ec437765254635493e63f to your computer and use it in GitHub Desktop.
Python3 Template

Python3 Template

This is a style I frequently use for self-contained command-line python scripts.

It distinctly separates:

  • Core functionality
  • Unit testing
  • Command-line behaviour - main_cli
  • Graphical (GUI) behaviour - main_gui
  • Command-line Parameters

I typically cut entire sections I don't intend to use. For example, I rarely include a GUI option.

Command-line

Add some numbers together with:

$ ./example.py 1 2
result = 3

Dump output to file instead:

$ ./example.py 1 2 -o result.log
$ cat result.log
result = 3

Call with --help to show options:

$ ./example.py --help
usage: example.py [-h] [--output FILE] [--gui] [NUMBER ...]

Add some numbers

positional arguments:
NUMBER

options:
-h, --help            show this help message and exit
--output FILE, -o FILE
                        file to write stuff to
--gui                 If set, will display a GUI to run function

Graphical User Interface (GUI)

The GUI can be accessed by running

$ ./example.py --gui

Opens a simple interface to enter text, and process it with a button-click.

Note: tkinter is only imported when the GUI is intended to be shown, so it's not imported if treated as a module, or the CLI is used.

Also note that there should be no core function implemented in the GUI code... the GUI is only there as an interface.

Import From Elsewhere

Can be imported from another script, and core function used. This should be what drives the core functionality -- in this case, the single function: func() -- from main()

>>> import example
>>> example.func('1', '2')
3

Unit Testing

Run tests using native unittest library:

$ UNITTEST=1 python3 -m unittest example -v
test_func (example.TestFunc) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Why UNITTEST=1? : the unit-test classes are only created if the environment variable UNITTEST exists. This is not mandatory, but is clener when importing as a module.

Pre-requisites

If your script imports non-builtin libraries, it's often helpful to add this to a requirements.txt file.

For example, if somewhere in my script I used pandas:

import pandas

Then I would create an accompanying requirements.txt file simply containing:

pandas

Then ask users of this script to install dependencies with:

$ python3 -m pip install -r requirements.txt

MIT License

For formality... please use this template however you'd like:

Copyright (c) 2023 Peter Boin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# Log files
*.log
#!/usr/bin/env python3
# ----- Core Functionality
import ast
def func(*params):
return sum(
ast.literal_eval(x) if isinstance(x, str) else x
for x in params
)
# ----- Command-line
def main_cli(value_list, output):
import contextlib
import sys
out = sys.stdout
with contextlib.ExitStack() as stack:
if output != '-':
out = stack.enter_context(open(output, 'w'))
# Invoke Core Func'
result = func(*value_list)
# Output stuff
out.write(f"result = {result}\n")
return 0 # return non-zero on error
# ----- Unit Tests
# Run with:
# $ UNITTEST=1 python3 -m unittest example.py -v
import os
if 'UNITTEST' in os.environ:
import unittest
class TestFunc(unittest.TestCase):
def test_func(self):
self.assertEqual(func(), 0)
self.assertEqual(func('1', '2'), 3)
self.assertEqual(func('0x10', '0b01', 10, 1.5, '0.6'), 29.1)
# ----- GUI (Graphical User Interface)
# If a GUI is what you want, implement it as classes / function
def main_gui(root):
import tkinter as tk
import re
# Interface Functions
def process(*args):
try:
values = re.compile(r'[\s,]+').split(widgets['text_box'].get())
result = func(*values)
widgets['label_ans'].config(text=f"result = {result}")
except Exception as e:
widgets['label_ans'].config(text=f"error: {e}")
raise
# Create & Pack Widgets
widgets = {
'label_info': tk.Label(root, text="Enter numbers:"),
'text_box': tk.Entry(root),
'button': tk.Button(root, text="Sum", command=process),
'label_ans': tk.Label(root, text=""),
}
widgets['text_box'].bind('<Return>', process)
for widget in widgets.values():
widget.pack()
return root # chain
# ----- Run from Command-line
# for example:
# $ python3 example.py 1 2 3
if __name__ == '__main__':
# CLI Arguments
import argparse
parser = argparse.ArgumentParser(description="Add some numbers")
parser.add_argument('values', metavar='NUMBER', nargs='*')
parser.add_argument(
'--output', '-o', metavar='FILE', default='-',
help="file to write stuff to",
)
parser.add_argument(
'--gui', default=False, action='store_const', const=True,
help="If set, will display a GUI to run function",
)
args = parser.parse_args()
# Execute
if args.gui:
import tkinter as tk
root = tk.Tk()
root.title("Simple Adder")
main_gui(root).mainloop()
else:
import sys
sys.exit(main_cli(
value_list=args.values,
output=args.output,
))
@fragmuffin
Copy link
Author

TODO:

  • use logging and -vv verbosity levels
  • screenshot of gui ⇾ readme
  • LICENSE as separate file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment