牛掰的python与unix

python的中心哲学

Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

IPython和Bash

IPython与Bash输出hello pyyu

[root@py_unix ~]# ipython
Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
Type "copyright", "credits" or "license" for more information.

IPython 3.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: print "hello pyyu"
hello pyyu
[root@py_unix ~]# echo "Hello pyyu"
Hello pyyu

IPython与Bash执行命令

Bash查看当前目录下的文件
[root@py_unix opt]# ls -l ./ 总用量 181564 -rw-r--r-- 1 root root 72325 6月 28 17:07 access.log -rw-r--r-- 1 root root 352 6月 28 17:09 get_ip.py drwxr-xr-x 13 root root 213 6月 13 17:51 mysql -rw-r--r-- 1 root root 185842760 8月 4 2016 mysql-5.5.50-linux2.6-x86_64.tar.gz drwxr-xr-x 2 root root 6 7月 3 16:49 redis
In [3]: import subprocess

In [4]: subprocess.c
subprocess.call          subprocess.check_call    subprocess.check_output  

In [4]: subprocess.call(["ls","-l","/opt"])
总用量 181564
-rw-r--r--  1 root root     72325 6月  28 17:07 access.log
-rw-r--r--  1 root root       352 6月  28 17:09 get_ip.py
drwxr-xr-x 13 root root       213 6月  13 17:51 mysql
-rw-r--r--  1 root root 185842760 8月   4 2016 mysql-5.5.50-linux2.6-x86_64.tar.gz
drwxr-xr-x  2 root root         6 7月   3 16:49 redis
Out[4]: 0

Subprocess与import的过程

牛掰的python与unix牛掰的python与unix
In [5]: subprocess.call(["some_command","some_argument","another_argument_or_path"])
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-5-541ed8cab1e8> in <module>()
----> 1 subprocess.call(["some_command","some_argument","another_argument_or_path"])

/usr/lib64/python2.7/subprocess.pyc in call(*popenargs, **kwargs)
    522     retcode = call(["ls", "-l"])
    523     """
--> 524     return Popen(*popenargs, **kwargs).wait()
    525 
    526 

/usr/lib64/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
    709                                 p2cread, p2cwrite,
    710                                 c2pread, c2pwrite,
--> 711                                 errread, errwrite)
    712         except Exception:
    713             # Preserve original exception in case os.close raises.

/usr/lib64/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
   1325                         raise
   1326                 child_exception = pickle.loads(data)
-> 1327                 raise child_exception
   1328 
   1329 

OSError: [Errno 2] No such file or directory
View Code

python脚本的运行

[root@py_unix home]# cat ls.py 
#!/usr/bin/env python
#python wrapper for ther ls command
import subprocess
subprocess.call(["ls","-l"])

[root@py_unix home]# python ls.py 
总用量 4
-rw-r--r-- 1 root root 106 8月  20 09:17 ls.py
[root@py_unix home]# cat osinfo.py 
#!/usr/bin/env python
# A System Information Gathering Script
import subprocess
#Command 1
uname = "uname"
uname_arg = "-a"
print "Gathering system information with %s command:\n" % uname
subprocess.call([uname,uname_arg])
#command 2
diskspace = "df"
diskspace_arg = "-h"
print "Gathering diskspace information %s command:\n" %diskspace
subprocess.call([diskspace,diskspace_arg])

输出结果:

[root@py_unix home]# python osinfo.py 
Gathering system information with uname command:

Linux py_unix 3.10.0-514.21.1.el7.x86_64 #1 SMP Thu May 25 17:04:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
Gathering diskspace information df command:

文件系统             容量  已用  可用 已用% 挂载点
/dev/mapper/cl-root   17G  3.8G   14G   22% /
devtmpfs             478M     0  478M    0% /dev
tmpfs                489M     0  489M    0% /dev/shm
tmpfs                489M  6.8M  482M    2% /run
tmpfs                489M     0  489M    0% /sys/fs/cgroup
/dev/sda1           1014M  184M  831M   19% /boot
tmpfs                 98M     0   98M    0% /run/user/0

python和bash查看内核信息和内存:

[root@py_unix home]# cat osinfo.sh 
#!/usr/bin/env bash
#A system Information Gathering Script
#Command 1
UNAME="uname -a"
printf "内核信息$UNAME \n\n"
$UNAME

#Command 2
DISKSPACE="df -h"
printf "内存信息$DISKSPACE \n\n"
$DISKSPACE
#############
注意Bash的空格

 subprocess模块

  加载subprocess模块仅仅是将可以使用的代码文件加载进来。也可以创建自己的模块或文件,拱以后重复使用,这与加载subprocess模块的方法相同。IPython shell的一个非常好的优点就是可以对模块或者文件检查,查看其内部可用的属性。

  使用Tab自动完成查看subprocess中可用的属性:

In [6]: subprocess.
subprocess.CalledProcessError  subprocess.STDOUT              subprocess.errno               subprocess.mswindows           subprocess.signal
subprocess.MAXFD               subprocess.call                subprocess.fcntl               subprocess.os                  subprocess.sys
subprocess.PIPE                subprocess.check_call          subprocess.gc                  subprocess.pickle              subprocess.traceback
subprocess.Popen               subprocess.check_output        subprocess.list2cmdline        subprocess.select              subprocess.types

查看subprocess.call的信息:

In [10]: subprocess.call?
Signature: subprocess.call(*popenargs, **kwargs)
Docstring:
Run command with arguments.  Wait for command to complete, then
return the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

retcode = call(["ls", "-l"])
File:      /usr/lib64/python2.7/subprocess.py
Type:      function

 

Python的优点之一是其交互式解释器,也称为shell。shell提供了一种能快速实现灵感、检验特性的方法,以及交互式的模块界面,能够将一些需要两三行脚本才能完成的任务一次性完成。

通常我们编写代码时,会采用同时运行文本编辑器和python的方式(稍后会有介绍,这实际上运行的就是Ipython),通过交互式的使用编辑器和shell,也就是在两者之间切换来完成程序的编写。

IPython集成了交互式Python的诸多优点。IPython具有卓越的Python shell,其性能远远优于标准Python的shell。IPython同时提供了基于控制台命令环境的定制功能,可以十分轻松的将交互式Python shell包含在各种Python应用中,甚至当作shell使用

 

Ipython提供了两类自动完成:完成(complete)与菜单完成(menu)。两者的差别在于'完成' 尽可能扩展当前的主题词,并提供一个可能的替换列表,而“菜单完成”会扩展主题词,直接匹配可以替换列表中的一个,并且如果连续按Tab键时,每一次都会切换到下一个可能的替换。IPython的默认自动完成是‘完成’。也可以通过设置修改。

强大的魔力函数

IPython有强大的功能。原因之一是它具有非常多的,内建的built-in魔力函数。

输入 牛掰的python与unix 按下Tab可以找出所有魔力函数.魔力函数的名字magic本身就具有魔力。运行magic可以打开一个分页的帮助文档,其中记录了所有IPython内建函数的用法。这个帮助文档包括函数名,函数的用法(用于何处),以及函数工作方式的描述。

UNIX Shell

UNIX shell提供了一个处理问题的统一方法,具有丰富的工具集,相当简练容易的语法、标准I/O流、管道、以及重定向等功能。

alias

In [16]: %alias nss netstat -tunlp
nss |grep 22

 

上一篇:【干货】用Python教你写一个批量ping


下一篇:轻松使用python调用系统shell执行命令行命令的几种方式!