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
相关文档:
继前篇《Import Module》(http://blog.csdn.net/xiadasong007/archive/2009/09/02/4512797.aspx),继续分析嵌入部分基础知识。这次不多说,有什么问题记得多查英文资料,国内的这方面知识少
还是来看代码,写完我就睡觉了~
#include "python/python.h"
#include <iostream>
using namespace std;
int ......
import sys
import os
import datetime
import time
class ArgsDealwith:
def arg_environment(self, args):
filepath = ('PYTHON_PATH', 'path')
for i in filepath:
&nbs ......
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 ......
#!/usr/bin/env python """
HMM module This module implements simple Hidden Markov Model class. It follows the description in
Chapter 6 of Jurafsky and Martin (2008) fairly closely, with one exception: in this
implementation, we assume that all states are initial states. @author: R ......