- iterating through directory
from pathlib import Path
for f in Path(".").glob("**/*.pdb"):
f.unlink()
from pathlib import Path
try:
last_ver = Path("version").read_text()
except FileNotFoundError as e:
print("error")
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__))
with open("TestClient.log",encoding="utf-8") as f:
c = 0
for l in f:
c = c + 1
print(f"{c}:{l}")
import subprocess
subprocess.run(["git", "fetch", "origin", "master"], check=True)
sys.executable
Command Line
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--remote_ip", required=True)
parser.add_argument("--sign", default=False, required=False, type=boolean_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():
print(f"{k} = {v}")
- read environment variables
import os
print(os.environ["PATH"])
- write environment variables
import os
os.environ["MY_ENV"] = "hello"
regular expression
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
dir(obj)
help("os")
import itertools
from pathlib import Path
p = Path(".")
for f in itertools.chain(p.rglob("*.exe"), p.rglob("*.dll")):
print(f)
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
0 评论:
Post a Comment