Python3 Scripting
Why Python scripting? Easy to learn and write, interactively, powerful built-in data types and object oriented. Included packages to support huge range of tasks.
The demos of this blog: https://github.com/chengdol/python-scripting
Common Modules for Scripting
math: Trig functions, sqrt, logarithms, exponentialspickle: Serialise / de-serialize objects for persistent storagerandom: Generate random numbers with various distributionsre: Regular expression pattern matching and substitutionstring: Comprehensive string formattingconfigparser: Configuration file parserbz2: gzip, read and write compressed filestarfile: Read and write tar archivesdatetime: Represent and manipulate dates and timeslogging: Log message generator with various backendsargparse: Parser for command-line optionsoptparse: Parse command-line argumentsclick: command-line argument toolkit, decoratoros: Interface to operating system servicessys: Access argv, stdin, stdout, etc.socket: Python binding for the traditional BSD socket APIhttp: Modules for client and server side http, and cookiesshutil: Copy / remove files and directory treesglob: Shell-style wildcard expansionxml: Processing of XML datahashlib: common interface to many hash functionssignal: single handlingsubprocess: execute command by spawn new processes, connect to their input/output/error pipes, and obtain their return codesshlex: parsing unix shell commands, for example, split long argumentssmtplib: email handlingthreading: threading operationstimeit: measure executing timepyyaml: parse yaml filerequests: simple http libraryretrying: retrying flaky functionpython-terraform: terraform wrapper
Work Environment
REPL
REPL: the interactive console. 这是最基本的一个python interactive shell, can be used for testing purpose.
IPython
ipython: the enhanced python interpreter, can run shell commands + REPL, make alias for arbitrary shell commands and with TAB completion.
How to install: yum install -y ipython3
Then in terminal, run ipython3
可以直接在ipython中运行比如ls -ltr, cd 之类的命令,这些都属于magic function:
1 | ## off magic |
Create alias:
1 | ## create alias 'findsymlinks' |
Run and edit files in IPython:
1 | run script.py |
对于不能直接运行的shell commads, use shell escape with prefix !, similar to vim feature:
1 | ## can store the output to a variable |
IDLE
How to install: yum install -y idle3
To run idle3, you need desktop environment.
Managing File System
找能实现Bash中功能的函数就行。
1 | ## walk around file system, wrap around Linux system call |
Interacting with Linux System
1 | import sys |
To parse parameters, use optparse module, see example in git repo 1_optparse-demo.py.
Besides optparse and argparse from the standard library, click module is a good alternative.
To get env varaible:
1 | import os |
这节的git repo例子很有意思5_signal-primes-v5.py, 6_timeout.py, 用signal handler 去改变条件变量的值,从而改变运行逻辑。之前一直在BASH中用trap去做终止前的处理。Linux has 2 signals set aside for user: SIGUSR1, SIGUSR2.
Executing Commands
Run external commands, for example, call other shell commands or executables by subprocess, similar to linux ().
1 | import subprocess |
关于python concurrency专门的总结: Python Concurrency
String Manipulation
Besides basic operation, it talks about datetime:
1 | import datetime |
然后讲了re module. 可以参考这节的git code.
Processing Text, Logging
For long running background service, logging is a must, we can log events into: file, syslog or systemd journal.
Logger has different handlers, for example: StreamHandler(stdout, stderr), FileHanlder, watchFileHandler, SysLogHandler, SockerHandler, JournalHandler, etc.
Logging levels: NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL.