Python Insights


This page is a collection of hints and insights into the use of Python. Although I have standardized on the use of Python3, there is still a lot of legacy code written in Python 2.7, and these are flagged where necessary. Assume Python 3 otherwise.

Sources are many, and are identified when I remember.

Formatting (including f Strings)

I have always had trouble remembering how to format formats. Here's a cheat sheet:
replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>
format_spec       ::=  [[fill] align] [sign] [z] [#] [0] [width] [grouping_option] [.precision] [type]
fill              ::=  <any character>
align             ::=  "<" | ">" | "=" | "^"
sign              ::=  "+" | "-" | " "
width             ::=  digit+
grouping_option   ::=  "_" | ","
precision         ::=  digit+
type              ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

But for a good, simple, cheat sheet on f strings, see f strings made simple

Mouse Functions

See the documentation for pyautogui


I saw this article in the Python hackers' page, and it sounded interesting, but I did not have time to read it at the time. So I am filing it for later perusal.

Hints from PyCoder's Weekly

The Right Way to Run Shell Commands From Python

original article

While I love Python's standard library, I believe one of its missing "batteries" is a better subprocess module. If you find yourself orchestrating lots of other processes in Python, then you should at least take a look at sh library:

    # pip install sh
    import sh

    # Run any command in $PATH...

    ls_cmd = sh.Command('ls')

    # If command is not in PATH:
    custom_cmd = sh.Command('/path/to/my/cmd')
    custom_cmd('some', 'args')

    with sh.contrib.sudo:
        # Do stuff using 'sudo'...

    # output to a file
(See original article for further information.)

This page is copyright, and maintained by John Hurst. 3 accesses all since
30 Nov 2023
My PhotoMy PhotoTrain Photo

Local servers: Localhost Newport Burnley Jeparit Reuilly Spencer (accessible only on local network.)
Public Web Servers: (not all may be active.)
Dynamically generated at 20231203:1933 from an XML file modified on 20230701:1613, by version 1.6.3.