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对网页的操作。
这篇简单说下如何通过网址下载网页,前提当然是 ......
模块
一.简介
模块基本上就是一个包含了所有你定义的函数和变量的文件。为了在其他程序中重用模块,模块的文件名必须以.py为扩展名。
例如:
#!/usr/bin/python
# Filename: using_sys.py
import sys
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n ......
import sys
import os
import datetime
import time
class ArgsDealwith:
def arg_environment(self, args):
filepath = ('PYTHON_PATH', 'path')
for i in filepath:
&nbs ......
Python中的异常
当你的程序中出现某些异常的状况的时候,异常就发生了。
一.处理异常
我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
例如:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('E ......
1.简单的将日志打印到屏幕
import
logging
logging.
debug(
'This is debug message'
)
logging.
info(
'This is info message'
)
logging.
warning(
'This is warning message'
)
屏幕上打印:
WARNING:root:This is warning ......