python shell脚本(主要讲管道操作的支持)
这里提供的只是一个支持管道的命令执行接口, 至于获取命令, 扩展自己的命令, 就不再赘述.
对于系统的命令, 可以直接调用这个接口方法, 多个命令支持管道操作. 发生错误时, 引发OSError.
1. 判断传入命令是否是字符串类型
2. 传入的每个命令.
3. 遍历所有命令.
4. 获取每个命令的命令及参数
5. 动态执行Popen, 并将返回值放入列表popens中
6. 动态执行构建的Popen, 第一个只有stdin不使用管道, 最后一个stdout指定为sys.stdout. 其余的都是PIPE
7. 遍历取出Popen对象, 将前一个对象的stdout写入到后一个对象的stdin中.
'''
Created on 2009-10-21
@author: selfimpr
@blog: http://blog.csdn.net/lgg201
@E-mail: lgg860911@yahoo.com.cn
@function: 测试过FreeBSD下可以使用. 是一个小练习, 作用是将系统命令作为参数传入, 执行. 接受的参数支持管道操作, 管道操作符使用|.
'''
from sys import stdout
from subprocess import Popen, PIPE
def pipecmd(cmdstr):
if isinstance(cmdstr, str): # estimate if the argument is string
cmds = cmdstr.split('|') # split intact cmdstr to sigle command
cmds = [cmd.strip() for cmd in cmds] # strip space character
length = len(cmds)
popens = []
for index, cmd in enumerate(cmds): # each all the commands
cmd_args = cmd.split(' ')
cmd_args = [arg.strip() for arg in cmd_args]
try:
#################
# get all the instance of Popen
#################
popens.append(eval('Popen(cmd_args%(stdin)s%(stdout)s)' % \
{'stdin': '' if index == 0 else ', stdin=PIPE', \
'stdout': ', stdout=stdout' if index == length - 1 else ', stdout=PIPE'}))
except OSError, e:
print 'arises os error'
#################
# process pipe
#################
prev = None
for index, popenobj in enumerate(popens):
if not prev:
prev = popenobj
continue
popenobj.stdin.write
相关文档:
刚刚写完Python嵌入部分的简单例子(差不多够现在用的啦~),接着看点实际的东西,如果没有这些应用的话,前面的嵌入也没有什么意义。嵌入的其他部分以后遇到再写,不必一下子把那些函数都弄懂,是吧~
OK,来看Python库中我认为最好玩的一部分,也就是Python对网页的操作。
这篇简单说下如何通过网址下载网页,前提当然是 ......
1. 打印变量和变量自显
>>> myString = 'Hello World!'
>>> print myString
Hello World!
>>> myString
'Hello World!'
因为: print 语句调用str()函数显示对象,而交互式解释器则调用repr()函数来显示对象
sys.stdout.write('hello')不会在末尾加上'\n',而print会
2. 打印文件
hand ......
Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various man ......
client:
import socket, sys
if __name__ == '__main__':
#处理参数
argv = sys.argv
if (len(argv)!=3) or (len(argv)==2 and argv[1]=='/?'):
print '>>>Useage:', argv[0], '<address> < ......
在讲述filter,map和reduce之前,首先介绍一下匿名函数lambda。
lambda的使用方法如下:lambda [arg1[,arg2,arg3,...,argn]] : expression
例如:
>>> add = lambda x,y : x + y
>>> add ......