python调用Linux脚本或者pk10盘口出租的几种方法

方法1:pk10盘口出租【企鹅217-1793-408】

os.system()

只得到命令成功与否的执行状态

>>> import os
>>> os.system('free -m')
total used free shared buffers cached
Mem: 474 463 11 0 13 29
-/+ buffers/cache: 420 54
Swap: 1023 415 608


>>> ret=os.system('free -m')
total used free shared buffers cached
Mem: 474 464 10 0 12 30
-/+ buffers/cache: 420 53
Swap: 1023 415 608
>>> print ret #返回状态码是0,表示shell执行成功
0


方法2:

os.popen

通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)

>>> import os
>>> output = os.popen('free -mt')
>>> print output.read()
total used free shared buff/cache available
Mem: 7823 3445 215 64 4162 3864
Swap: 3071 270 2801
Total: 10895 3716 3016


方法3:

commands.getstatusoutput() && commands.getoutput()

commands.getstatusoutput() 既可以输出执行成功与否的状态,也会输出执行结果

commands.getoutput() 只输出执行结果

>>> import commands
>>> (status, output) = commands.getstatusoutput('free -mt')
>>> print status
0
>>> print output
total used free shared buff/cache available
Mem: 7823 3475 188 64 4159 3834
Swap: 3071 270 2801
Total: 10895 3746 2989


>>> output = commands.getoutput('free -mt')
>>> print output
total used free shared buff/cache available
Mem: 7823 3475 188 64 4159 3834
Swap: 3071 270 2801
Total: 10895 3746 2989
当命令调用错误时:

>>> (status, output) = commands.getstatusoutput('free -aaa')
>>> print status
256
>>> print output
free: invalid option -- 'a'
Usage:
free [options]
Options:
-b, --bytes show output in bytes
-k, --kilo show output in kilobytes
-m, --mega show output in megabytes
-g, --giga show output in gigabytes
--tera show output in terabytes
-h, --human show human-readable output
--si use powers of 1000 not 1024
-l, --lohi show detailed low and high memory statistics
-t, --total show total for RAM + swap
-s N, --seconds N repeat printing every N seconds
-c N, --count N repeat printing N times, then exit
-w, --wide wide output
--help display this help and exit
-V, --version output version information and exit
For more details see free(1).

猜你喜欢

转载自www.cnblogs.com/xinghezhuan/p/10488814.html