我,python,也要一行程式

weixin_34146805發表於2018-04-08

思路這種東西,對於非科班出身的我來說,太重要了
因為我不會捧著厚厚的一本書,例如《python從入門到放棄》,什麼的去看。自然不會系統理論的去學習
通常是遇到問題,我就去百度,百度不到,我就google。直到找到適合的方法。
所以說,對於python,我不會像shell,awk,perl那樣去敲一行程式,都是寫成xxx.py的指令碼去執行。

但是對於嚴酷的生產環境來說,你在伺服器上做太多個人的指令碼顯然是給自己挖坑。
秉承快速理念,今天研究一下Python的一行程式。契機源於知乎上看到的一篇文章。

首先python一行程式的引數是什麼,遇到這些問題請像我一樣,命令加-h去檢視

PS C:\Users\Administrator> python -h
usage: C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I     : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO    : remove doc-strings in addition to the -O optimizations
-q     : don't print version and copyright messages on interactive startup
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization
-u     : unbuffered binary stdout and stderr, stdin always buffered;
         also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version)
         when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>;<exec_prefix>).
               The default module search path uses <prefix>\lib.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
   to seed the hashes of str, bytes and datetime objects.  It can also be
   set to an integer in the range [0,4294967295] to get hash values with a
   predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
   on Python memory allocators. Use PYTHONMALLOC=debug to install debug
   hooks.

如上,就這一句
-c cmd : program passed in as string (terminates option list)
好了,來嘗試做一些標準操作

例如,判斷一個長字串裡每個字元出現了多少次,用列表的count方法

PS C:\Users\Administrator> python -c "var='sdfesdvwetohooodfedsfacbfdaczdfew';varlist=list(var);newlist=list(set(varlist));[print('element is '+em+' count is '+str(varlist.count(em))) for em in newlist]"
element is e count is 4
element is o count is 4
element is s count is 3
element is h count is 1
element is a count is 2
element is z count is 1
element is d count is 6
element is t count is 1
element is w count is 2
element is b count is 1
element is c count is 2
element is f count is 5
element is v count is 1

如果嫌太長,就可以把分號當作一個回車來輸入,如下

PS C:\Users\Administrator> python -c "var='sdfesdvwetohooodfedsfacbfdaczdfew'
>> varlist=list(var)
>> newlist=list(set(varlist))
>> [print('element is '+em+' count is '+str(varlist.count(em))) for em in newlist]"#這個迴圈需要用[]符號圈起來
element is h count is 1
element is s count is 3
element is d count is 6
element is a count is 2
element is z count is 1
element is w count is 2
element is o count is 4
element is f count is 5
element is t count is 1
element is c count is 2
element is v count is 1
element is e count is 4
element is b count is 1

有什麼意義,意義在於每個人的專精不同,然後系統環境又存在差異,多一種思路對於應對特定環境有所幫助。
用Python好處是書寫方便,文件多,模組多。

再舉個例子,目前環境限制如下
在一個python3的容器內,無法新增expect,只能用python的pexpect模組。
對anodest01這臺做一個操作,在vagrant目錄下建立一個檔案。

[vagrant@anodest01 ~]$ uname -n;date
anodest01
Sun Apr  8 09:21:33 UTC 2018
[vagrant@anodest01 ~]$ ls -lt
total 0

執行命令

root@24ebede9724d:/# python -c "import pexpect
> pwd='vagrant'
> process=pexpect.spawn('ssh vagrant@192.168.8.82 touch from_master_docker_py3')
> process.expect('[Pp]assword')
> process.sendline(pwd)
> process.expect(pexpect.EOF)"

在anodest01上看效果,建立完成

[vagrant@anodest01 ~]$ uname -n;date
anodest01
Sun Apr  8 09:23:02 UTC 2018
[vagrant@anodest01 ~]$ ls -lt
total 0
-rw-rw-r--. 1 vagrant vagrant 0 Apr  8 09:22 from_master_docker_py3

以上就是今天研究的例項,但目前來說使用上沒有多複雜,對於複雜的需求是什麼呢

自然是轉譯符的問題,python -c "",預設是使用了雙引號引用,裡面的字元什麼的都要用單引號,如果遇到了需要雙引號的情況,大家還需要在實際場景中多嘗試和努力。

相關文章