методі для запуска команд шелла из питона

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python
import os, popen2, fcntl, select, string
def makeNonBlocking(fd):
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
try:
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY)
except AttributeError:
fcntl.fcntl(fd, os.F_SETFL, fl | os.FNDELAY)
def getCommandOutput(command):
child = popen2.Popen3(command, 1) # capture stdout and stderr from command
child.tochild.close() # don't need to talk to child
outfile = child.fromchild
outfd = outfile.fileno()
errfile = child.childerr
errfd = errfile.fileno()
makeNonBlocking(outfd) # don't deadlock!
makeNonBlocking(errfd)
outdata = errdata = ''
outeof = erreof = 0
while 1:
ready = select.select([outfd,errfd],[],[]) # wait for input
if outfd in ready[0]:
outchunk = outfile.read()
if outchunk == '': outeof = 1
outdata = outdata + outchunk
if errfd in ready[0]:
errchunk = errfile.read()
if errchunk == '': erreof = 1
errdata = errdata + errchunk
if outeof and erreof: break
select.select([],[],[],.1) # give a little time for buffers to fill
err = child.wait()
if err != 0:
raise RuntimeError, '%s failed w/ exit code %d\n%s' % (command, err, errdata)
return outdata
def getCommandOutput2(command):
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError, '%s failed w/ exit code %d' % (command, err)
return data
def free_on_disk():
return int(string.split(getCommandOutput("df --block-size=1 / | grep '^/dev/hda1'"))[3])