Python的一些小知识点_6


1.用Python执行系统命令

首先,确定搜索关键字:

http://search.aol.com/aol/search?q=python+execute+linux+system+command

用Python执行系统命令时,’\r\n’可能会引起的问题:

http://stackoverflow.com/questions/26555814/using-os-system-in-python-to-execute-linux-command

如何知道os.system()函数是使用哪个shell执行的命令?

http://stackoverflow.com/questions/905221/os-system-execute-command-under-which-linux-shell

os.system() just calls the system() system call (“man 3 system”). On most *nixes this means you get /bin/sh.

subprocess.Popen()的executable参数  #可以指定使用Bash而不是默认的/bin/sh

在Python中如何获取调用系统命令执行的返回内容?

http://stackoverflow.com/questions/3791465/python-os-system-for-command-line-call-linux-not-returning-what-it-should

如果想要获取系统命令执行后的返回内容,应该使用subprocess.Popen() 或者 os.popen() 而不是os.system(),原因如下:

python_exec_command

http://stackoverflow.com/questions/1007855/popen-and-python

实例:

http://www.cyberciti.biz/faq/python-execute-unix-linux-command-examples/

 

2.如何获取Linux系统的网卡接口列表

首先,确定搜索关键字:

http://search.aol.com/aol/search?q=use+python+to+get+interface+name+%27%2Fproc%2Fnet%2Fdev%27

# grep -A1 'lo:' /proc/net/dev | grep -v 'lo:' | awk -F':' '{print $1}'
  eth0

# grep -A1 'lo:' /proc/net/dev | grep -v 'lo:' | awk -F':' '{print $1}' | sed 's/[[:space:]]//g'
eth0


In [5]: print os.popen("grep -A1 'lo:' /proc/net/dev | grep -v 'lo:' | awk -F':' '{print $1}' | sed 's/[[:space:]]//g'").read()
eth0
In [6]: print os.popen("grep -A1 'lo:' /proc/net/dev | grep -v 'lo:' | awk -F':' '{print $1}'").read().strip()
eth0

总结:可以通过Python调用系统命令(ip/ipconfig/netstat) 或 解析系统文件(/proc/net/dev)来得到。

 

3.在Python中判断某个字符串/数字是否在某一集合中的速度快慢对比

是 tuple() 快,还是 set() 快?

http://search.aol.com/aol/search?q=python+set+in+efficiency


最后可知,判断某一元素是否在某一集合中时,最佳的方案是 set ,list和tuple的复杂度为O(n),而 set 只有O(1):

python_complexity_info

https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

 

4.Python的内置函数:any()和all()的技巧

http://search.aol.com/aol/search?q=python+any+true

 

5.Python中的list和tuple的相互转换
It should work fine, don't use tuple, list or other special names as a variable name. It's probably whats causing your problem.

>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)

 

6.用Python解压gzip字符串
#!/usr/bin/env python
# coding=utf-8
import sys, zlib, binascii

try:
    with open(sys.argv[1], 'rb') as fp: original_str = fp.read()
except IOError as e:
    print e
if len(original_str) > 2 and '1F8B' == binascii.hexlify(original_str[:2]).upper():
    try:
        data = zlib.decompress(original_str, 16+zlib.MAX_WBITS)
    except:
        print 'decompress error...'
        sys.exit(1)
    if len(sys.argv) == 3:
        with open(sys.argv[2], 'wb') as fp: fp.write(data)
    else:
        print 'Length:', len(data)
        print data

 

,

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注