Thursday, October 11, 2018

Replacing bash with python3

  • iterating through directory
from pathlib import Path
for f in Path(".").glob("**/*.pdb"):  
    f.unlink()
  • reading file
from pathlib import Path
try:  
 # open file `version`, read all contents
    last_ver = Path("version").read_text()
except FileNotFoundError as e:
 print("error")
  • writing file
#open prepare.bat and write content hello
with open("prepare.bat", mode="w") as f:  
    f.write("hello\n")
  • directory of current script
import os
DIR = os.path.dirname(os.path.abspath(__file__))
  • read all lines
with open("TestClient.log",encoding="utf-8") as f:
    c = 0
    for l in f:
        c = c + 1
        print(f"{c}:{l}")
  • starting process
import subprocess
#run git and throw exception if return code is non-zero
subprocess.run(["git", "fetch", "origin", "master"], check=True)
  • current python exe path
sys.executable

Command Line

  • command line arguments
def parse_args():  
    parser = argparse.ArgumentParser()  
    parser.add_argument("--remote_ip", required=True)  
    parser.add_argument("--sign", default=False, required=False, type=boolean_string)  
    # using type=bool will case sign to be true will any non-empty string
    parser.add_argument("--check_in", default=False, required=False, type=boolean_string)  
    try:  
        return parser.parse_args()  
    except:  
        exit(1)
args = parse_args()
microDir = args.remote_ip
def boolean_string(s):  
    if s.upper() not in {'FALSE', 'TRUE'}:  
        raise ValueError('Not a valid boolean string')  
    return s.upper() == 'TRUE'

Environment variable

  • list environment variables
import os
for k, v in os.environ.items():
 # all k in Windows system will be upcase
 print(f"{k} = {v}")
  • read environment variables
import os
# print environment variable PATH
print(os.environ["PATH"])
  • write environment variables
import os
# set MY_ENV to myself and my child processes created afterwards
os.environ["MY_ENV"] = "hello"

regular expression

  • match and extract
import re
ip = "192.168.0.2"
m = re.match("(\d+).(\d+).(\d+).(\d+).(\d+)", ip)
v = [0,0,0,0]
if m:
 for i in range(0, 4):
  v[i] = m[i+1]

Python tips

  • grammar & buildin library

# list attributes of an obj
dir(obj)

# get help document of something
help("os")

# chaining to generators
import itertools
from pathlib import Path
p = Path(".")  
for f in itertools.chain(p.rglob("*.exe"), p.rglob("*.dll")):  
    print(f)

# format printting
name = "shawn"
msg = f"hello, {shawn}"

  • debug
    – use python shell to try out single line scripts
    – use Ctrl+N (Menu: File -> New File) in python shell to try out multiple lines scripts