Some Python hints for myself as a Python novice. Especially differences to C/C#/Java ...
See: Coding Conventions for a big mess ...
- Data Types
- Control Flow
- Files and Folders
- System
- Console
- Web
- Open Office (pandas)
- External Processes
x = "3"
y = 3
z = 3.0
x = str(3)
y = int(3)
z = float(3)
print(type(x))
def func():
global a
a = "fantastic"
func()
print("Global: " + a)
Various methods: https://www.w3schools.com/python/python_strings_methods.asp
r"C:\abc"
f"text with {variable}"
f"text with {variable:.2f}" # two decimals of a float
fr"C:\text\{variable}"
- r: text ignoring escape chars (especially for Windows paths)
- f: format variable content into the string
Links:
- Escape chars: https://www.w3schools.com/python/python_strings_escape.asp
- Formatting: https://www.w3schools.com/python/python_string_formatting.asp
Contains and StartsWith:
if "string" in myString:
...
if myString.startswith(prefix):
...
for line in textBlob:
print(line)
text[1:3] # including 1, excluding 3
text[:4] # from start, excluding 4
text[4:] # including 4 to the end
text = "a, b"
print(a.split(",")) # returns ['a', ' b']
text.upper()
text.lower()
text.strip() # remove leading and trailing spaces
text.replace("a", "b")
some_names = [
"Alice",
"Bob",
]
list_in_list = [
["Alice", "Merton"],
["Bob", "Hope"],
]
alice = some_names[0]
n = len(some_names)
for name in some_names:
print(name)
some_names.pop(0) # removes first item
some_names.remove("Alice")
Other list/array actions: https://www.w3schools.com/python/python_arrays.asp
Key:Value store.
person = {
"first": "Alice",
"name": "Merton",
"year": 1993
}
person = dict(first = "Alice", name = "Merton", year = 1993)
print(person)
print(person["name"])
print(len(person))
https://www.w3schools.com/python/python_dictionaries.asp
if a==b and not c==d or e!=f:
print(a)
elif not a==b:
print(b)
else:
print(c)
match variable:
case "a" | "b":
# do a
case _:
# default
return a, b, c
try:
# action
except PermissionError:
# reaction
except OSError as error:
if error.errno == 41:
# more ...
except Exception as error:
# more ...
exit(1)
Unfortunately, there is no exit code standard ... https://stackoverflow.com/questions/1101957/are-there-any-standard-exit-status-codes-in-linux
Maybe some common ones:
- 0: ok
- 1: general error
- 2: command line usage error
- x: other failure ...
import os
os.path.exists(dirOrFile)
os.path.isdir(dir)
os.path.isfile(file)
os.path.getsize(file)
joinedPath = os.path.join(dir, file)
extension = os.path.splitext(file)[1]
cwd = os.getcwd()
os.chdir(dir)
for dirsAndFiles in os.listdir(dir):
...
os.makedirs(dir)
os.remove(file)
os.rmdir(dir)
with open("infile.txt", 'r', encoding='utf8') as infile:
with open("outfile.txt", 'w', encoding='utf8') as outfile:
while line := infile.readline():
outfile.write("pre-" + line + "\n")
File modes: https://www.w3schools.com/python/python_file_handling.asp
import time
time.sleep(100/1000) # sleep 100 ms
Parsing command line arguments:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--input', '-i', help='input file', required="True")
parser.add_argument('--verbose', '-v', help='show verbose', action='store_true', dest="show_verbose")
parser = parser.parse_args(sys.argv[1:])
if parser.show_verbose:
print(parser.input)
import os
userprofile = os.environ['USERPROFILE']
import platform
name = platform.node()
Not perfect, will probably only work with VS Code:
isDebuggerRunning = os.environ.get('DEBUGPY_RUNNING') == "true"
print("\rtext", end='', flush=True)
- \r "carriage return" will point cursor at the start of the console line
- end='' avoids a newline (console won't jump to the next line)
- flush=True prints out immediately on (Windows) console (as end='' causes the output to be buffered and not shown immediately)
Wait for "enter key" pressed:
text = input("Enter a text:")
Wait for single "any key" press (Windows only, there seems to be no easy portable way)
import msvcrt
selected = msvcrt.getch().decode('ASCII')
Set the title of the console window:
system("title " + title)
https://stackoverflow.com/questions/287871/how-do-i-print-colored-text-to-the-terminal
CRED = '\33[31m'
CGREEN = '\33[32m'
CBLUE = '\33[34m'
CEND = '\33[0m'
print(CRED + "red" + CEND)
print(CGREEN + "green" + CEND)
print(CBLUE + "blue" + CEND)
import urllib.request
urllib.request.urlopen("url").read()
Use pandas for handling of data e.g. in LibreOffice .ods files.
https://www.w3schools.com/python/pandas/default.asp
pip install pandas
TODO: use venv
import pandas as pd
df = pd.read_excel("test.ods", "sheet", engine="odf")
print(df)
for index, row in df.iterrows():
contentFromCell = str(row["Column Header"])
subprocess.run will wait until the child process has finished.
import subprocess
command = "doit parameter"
result = subprocess.run(command, stdout=sys.stdout)
returned = result.returncode
command = "choco outdated"
result = subprocess.run(command.split(), capture_output=True, text=True)
returned = result.returncode
for line in result.stdout.splitlines():
...
command = f"choco list -lo -r -y"
with open("output.txt", 'w', encoding='utf8') as outfile:
subprocess.run(command, stdout=outfile, stderr=subprocess.STDOUT)
The DETACHED_PROCESS flag is Windows specific! There seems to be no easy platform independent way to do this 👎
subprocess.Popen(start, creationflags=subprocess.DETACHED_PROCESS)
⚠️ Warning: If running in a debugger, closing the debug session will stop all processes created here!
Platform independent process handling.
pip install psutil
TODO: use venv
for proc in psutil.process_iter(attrs=['pid', 'name']):
if proc.info['name'] == "explorer.exe":
...
proc.terminate()
proc.kill()
Terminate is gracefully shutdown, kill is hard kill.