程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

14 Python command line cold weapons, one more powerful than the other!

編輯:Python

Python It comes with some command line tools , Can be used to quickly process work . I call these command-line tools Cold weapon , When there is no handy tool, it can be used instead . These tools are python Standard module , have main function , Use it directly python -m Command execution , Most can be used -h/--help view help .

1. http service

Start a http Static file service

# python -m http.server
Serving HTTP on :: port 8000 (http://[::]:8000/) ...

2. json format

format json data

# echo '{"amount":3.4}' | python -m json.tool
{
    "amount": 3.4
}

3. Visual editor and shell

idlelib The module is based on tkinter, Can be used as editor and shell Use . File editor effect .

python -m idlelib myapp/example.py

shell effect

python -m idlelib

gui-shell

4. python Application packaging

structure myapp Directory as follows :

├── myapp
│   ├── example.py
│   └── hello.py

The codes are as follows :

# example.py
import hello
def main():
   print('Hello World')
   hello.say_hello("python")
   
if __name__=='__main__':
   main()
# hello.py
def say_hello(name):
 print("hello",name)

Will the whole myapp Packaged as an application , After the command is executed, a file named myapp.pyz Applications .

python -m zipapp myapp -m "example:main"

Use python Run the application directly

# python myapp.pyz
Hello World
hello python

5. ROT13 encryption

rot13(rotate by 13 places) It's a simple replacement password , It's a variant of Caesar's code .rot13 Offset original text 13 Bits form ciphertext , Because English has a total of 26 position , So the ciphertext is shifted again 13 It will return to the original text . The formula : rot13(rot13(xxx))=xxx.

# echo "xxx" | python -m encodings.rot_13
Tvir zr n fgne

As a little egg , Welcome to decipher xxx Value

6. base64 code

To a string base64 code

# echo "haha" | python -m base64
aGFoYQo=
# echo "aGFoYQo=" | python -m base64 -d
haha

base64 File encoding is also supported . Write test code

# sample.py
def main():
   print('Hello World')
   
if __name__=='__main__':
   main()

Compile the code into base64 character string

# python -m base64 sample.py
CmRlZiBtYWluKCk6CiAgIHByaW50KCdIZWxsbyBXb3JsZPCfkYwnKQogICAKaWYgX19uYW1lX189
PSdfX21haW5fXyc6CiAgIG1haW4oKQo=

Execute the compiled code

# echo "CmRlZiBtYWluKCk6CiAgIHByaW50KCdIZWxsbyBXb3JsZPCfkYwnKQogICAKaWYgX19uYW1lX189
PSdfX21haW5fXyc6CiAgIG1haW4oKQo=" | python -m base64 -d | python
Hello World

Similar can be used uu(Unix-to-Unix encoding) Coding code :

# python -m uu sample.py
begin 644 sample.py
M"F1E9B!M86EN*"DZ"B @('!R:6YT*"=(96QL;R!7;W)L9/"?D8PG*[email protected](" *
C:[email protected]]N86UE7U\]/2=?7VUA:6Y?7R<Z"B @(&UA:6XH*0H
end

Use quopri(Encode and decode MIME quoted-printable data) Coding code :

# python -m quopri -t sample.py
def=20main():
=20=20=20print('Hello=20World=F0=9F=91=8C')
=20=20=20
if=20__name__=3D=3D'__main__':
=20=20=20main()

7. mime distinguish

Identification file or url Of mime type

# python -m mimetypes https://docs.python.org/3/library/mimetypes.html
type: text/html encoding: None  # html
# python -m mimetypes https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png
type: image/png encoding: None  # png
# python -m mimetypes sample.py
type: text/x-python encoding: None  # python file
# python -m mimetypes sample.py.gz
type: text/x-python encoding: gzip  # python file ,gzip Compress 

8. see python environmental information

python -m sysconfig
Platform: "macosx-10.9-x86_64"
Python version: "3.8"
Current installation scheme: "posix_prefix"
Paths:
 data = "/Users/yoo/work/yuanmahui/python/.venv"
 include = "/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8"
 ...
Variables:
    ...
 PYTHON = "python"
 PYTHONFRAMEWORK = "Python"
 PYTHONFRAMEWORKDIR = "Python.framework"
 PYTHONFRAMEWORKINSTALLDIR = "/Library/Frameworks/Python.framework"
 ...

You can also use the following command to view the system path

# python -m site
sys.path = [
    '/Users/yoo/work/yuanmahui/python/python-tools',
    '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip',
    '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8',
    '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload',
    '/Users/yoo/work/yuanmahui/python/.venv/lib/python3.8/site-packages',
]
USER_BASE: '/Users/yoo/Library/Python/3.8' (exists)
USER_SITE: '/Users/yoo/Library/Python/3.8/lib/python/site-packages' (exists)
ENABLE_USER_SITE: False

9. Compile the script

compileall You can compile python Script .myapp The catalog has 2 individual py Script

# ll myapp
total 16
-rw-r--r--  1 yoo  staff   118B  2 26 23:03 example.py
-rw-r--r--  1 yoo  staff    43B  2 26 23:03 hello.py

Compile the script

# python -m compileall myapp
Listing 'myapp'...
Compiling 'myapp/example.py'...
Compiling 'myapp/hello.py'...

View the compilation results

tree myapp -L 3
myapp
├── __pycache__
│   ├── example.cpython-38.pyc
│   └── hello.cpython-38.pyc
├── example.py
└── hello.py
1 directory, 4 files

10. Compress and decompress

Create and unzip tar package

# python -m tarfile -c myapp.tar myapp  #  establish myapp.tar  Compressed package
# python -m tarfile -e myapp.tar myapp2 #  decompression myapp.tar  To  myapp2 Catalog 

Use gzip Compressed files

# python -m gizp sample.py
# python -m gzip -d sample.py.gz

Use zip Package files

# python -m zipfile -c myapp.zip myapp
# python -m zipfile -e myapp.zip myapp2

Be careful : zipfile and zipapp Dissimilarity , The latter is to generate an executable app

11. telnet Tools

No, telnet The tool python This can be done in containers :

# python -m telnetlib -d redis 6379  #  Connect redis
monitor
Telnet(redis,6379): send b'monitor\n'
Telnet(redis,6379): recv b'-NOAUTH Authentication required.\r\n'
-NOAUTH Authentication required.

also nntplib && ftplib Two tools , It should be rarely used , No introduction

12. Performance and debugging tools

Self contained timeit You can test the performance data of the script

# python -m timeit '"-".join([str(n) for n in range(100) if n%2 == 0])'  #  Take a module and find an even number
20000 loops, best of 5: 12.5 usec per loop
# python -m timeit '"-".join([str(n) for n in range(0,100,2)])'  #  Stepping
50000 loops, best of 5: 8.85 usec per loop
# python -m timeit '"-".join([str(n) for n in range(100) if n&1 == 0])'  #  Bit operation determines parity
20000 loops, best of 5: 14.3 usec per loop

Unscientific 1: Bit operation is even slower than modulo ?

If it's not a string but a script :

def test_normal():
 tmp = ""
 for x in range(100):
  if x % 2 == 0:
   if tmp:
    tmp = tmp+"-"+str(x)
   else:
    tmp = str(x)
 return tmp
if __name__ == '__main__':
 print(test_normal())

It can be used in the following ways

# python -m base64 test_string_join.py | python -m base64 -d | python -m timeit
50000000 loops, best of 5: 5.33 nsec per loop

Unscientific 2: 50000000 The loop just needs 5.33 nanosecond , The previous use cases 20000 Recycling needs 12.5 Microsecond

There are also... In the standard library pdb && profile && pstats It's complicated to use , I will not introduce

pypy3 -m timeit '[{} for n in range(1000)]'
WARNING: timeit is a very unreliable tool. use pyperf or something else for real measurements
pypy3 -m pip install pyperf
pypy3 -m pyperf timeit '[{} for n in range(1000)]'
------------------------------------------------------------
100000 loops, average of 7: 7.3 +- 0.107 usec per loop (using standard deviation)
[[email protected]_szfsfz_work1 config]$ pypy3 -m pyperf timeit '[{} for n in range(1000)]'
........
Mean +- std dev: 8.42 us +- 0.25 us
[[email protected]_szfsfz_work1 config]$
[[email protected]_szfsfz_work1 config]$
[[email protected]_szfsfz_work1 config]$
[[email protected]_szfsfz_work1 config]$ pypy3 -m pyperf timeit '[dict() for n in range(1000)]'
.........
Mean +- std dev: 29.6 us +- 1.1 us

13. pydoc

View in local service mode python Code documentation

# python -m pydoc -p 8080  #  Start a web service
Server ready at http://localhost:8080/
Server commands: [b]rowser, [q]uit
server> b

The document effect is shown in the figure below

14. test

perform python Self contained test cases , Check which features the system supports

# python -m test.regrtest -u cpu
== CPython 2.7.16 (default, Jun 5 2020, 22:59:21) [GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc-
==   Darwin-19.6.0-x86_64-i386-64bit little-endian
==   /private/var/folders/mv/3vgd3mdx2453clfcst7qlm280000gn/T/test_python_13470
== CPU count: 12
Run tests sequentially
0:00:00 load avg: 2.53 [  1/404] test_grammar
...
= Tests result: FAILURE ==
363 tests OK.
5 tests failed:
    test_import test_posix test_py_compile test_rlcompleter
    test_scriptpackages
36 tests skipped:
    test_al test_bsddb test_bsddb3 test_cd test_cl test_codecmaps_cn
    test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr
    test_codecmaps_tw test_curses test_epoll test_gdb test_gdbm
    test_gl test_imgfile test_largefile test_linuxaudiodev test_msilib
    test_ossaudiodev test_poll test_py3kwarn test_smtpnet
    test_socketserver test_spwd test_startfile test_sunaudiodev
    test_timeout test_tk test_tools test_ttk_guionly test_urllib2net
    test_urllibnet test_winreg test_winsound test_zipfile64
2 skips unexpected on darwin:
    test_spwd test_tools
Total duration: 5 min 23 sec
Tests result: FAILURE

From test case , You can see osx Support fork, I won't support it epool and poll.

0:00:47 load avg: 1.79 [138/404] test_fork1
...
0:00:39 load avg: 1.59 [125/404] test_epoll
test_epoll skipped -- test works only on Linux 2.6
...
0:02:42 load avg: 2.41 [257/404/1] test_poll
test_poll skipped -- select.poll not defined -- skipping test_poll
0:02:42 load avg: 2.41 [258/404/1] test_popen -- test_poll skipped

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved