Merge branch 'master' of git.calculate.ru:/calculate-lib

develop
Самоукин Алексей 14 years ago
commit 08148328bb

@ -20,6 +20,7 @@ from random import choice
import os
import types
import subprocess
from subprocess import Popen,PIPE,STDOUT
import stat
from shutil import copytree, rmtree
import ctypes
@ -134,6 +135,106 @@ class scanDirectory:
break
return ret
class process:
"""Execute system command by Popen
Example:
#execute program and get result
if process("/bin/gzip","/boot/somefile").success():
print "Gzip success"
#unzip and process unzip data by cpio (list files)
processGzip = process("/bin/gzip","-dc","/boot/initrd")
processCpio = process("/bin/cpio","-tf",stdin=processGzip)
filelist = processCpio.readlines()
#execute command and send data
processGrub = process("/sbin/grub")
processGrub.write("root (hd0,0)\n")
processGrub.write("setup (hd0)\n")
processGrub.write("quit\n")
isok = processGrub.success()
#union stdout and stderr
process("/bin/ls","/",stderr=STDOUT)
"""
def __init__(self,command,*params,**kwarg):
if not "stdin" in kwarg:
stdin=self._defaultStdin
else:
stdin=kwarg["stdin"].getStdout
self.stderr = kwarg.get("stderr",PIPE)
self.command = [command] + list(params)
self.stdin = stdin
self.iter = None
self.pipe = None
self.cacheresult = None
self.communicated = False
def _open(self):
"""Open pipe if it not open"""
if not self.pipe:
self.pipe = Popen(self.command,
stdout=PIPE,
stdin=self.stdin(),
stderr=self.stderr)
def _defaultStdin(self):
"""Return default stdin"""
return PIPE
def getStdout(self):
"""Get current stdout"""
self.close()
return self.pipe.stdout
def write(self,data):
"""Write to process stdin"""
self._open()
self.pipe.stdin.write(data)
self.pipe.stdin.flush()
def close(self):
"""Close stdin"""
if self.pipe:
self.pipe.stdin.close()
def read(self):
"""Read all data"""
self._open()
if not self.cacheresult:
self.cacheresult = self.pipe.communicate()[0]
return self.cacheresult
def readlines(self):
"""Read lines"""
return self.read().split('\n')
def __iter__(self):
"""Get iterator"""
if not self.iter:
self.iter = iter(self.readlines())
return self.iter
def next(self):
"""Next string from stdout"""
return self.__iter__().next()
def returncode(self):
"""Get return code"""
self._open()
if self.pipe.returncode == None:
self.cacheresult = self.pipe.communicate()
return self.pipe.returncode
def success(self):
"""Success or not"""
return self.returncode() == 0
def failed(self):
"""Failed or not"""
return self.returncode() != 0
def runOsCommand(cmd,inStr=None,ret_first=None,env_dict=None,ret_list=False):
"""Выполняет внешнюю программу

Loading…
Cancel
Save