一般來說,用shell的方便之處在於,能夠直接調用linux系統命令,方便的得到結果。
但是shell scprit的約束重重(這裡不再講了)。下面說一下在C和python中如何調用linux命令、得到返回值並得到輸出
1. python,使用os庫/commands庫
方法1)使用commands.getstatusoutput方法,這是一個神奇的方法,能夠直接得到返回值以及命令輸出。官網說明:http://docs.python.org/library/commands.html
import os
import commands
status,output=commands.getstatusoutput(cmdstr)
#***********************下面代碼是判斷返回值**********************************************************
if False==os.WIFEXITED(status) or 0!=os.WEXITSTATUS(status):
self.logging.info("check port false. port [%s] has not been listened. cmdstr: [%s]", port, cmdstr)
return False
self.logging.info("check port true. port [%s] has been listened. cmdstr: [%s]", cmdstr)
return True
status是返回值,ouput是輸出
#但是這種方法存在一個問題,就是如果命令中(cmdstr)含有&符號,這個命令會出錯,此時,需要使用os.system方法
方法2)使用os.system
status = os.system(cmdstr)
status是返回值,得不到輸出,檢查的方法如上
方法3)使用os.popen,這是一個和C相似的方法,既能得到返回值,也能得到輸出,缺點是用起來稍微麻煩一些
p=os.popen('ssh 10.3.16.121 ps aux | grep mysql')
x=p.read()
print x
p.close()
p相當於打開的一個文件
方法4) 使用 subprocess模塊,這個是比較新的模塊,要替代
os.system
os.spawn*
os.popen*
popen2.*
commands.*
這些模塊。 subprocess應用實例:
subprocess.call(args,
*, stdin=None, stdout=None, stderr=None, shell=False)
import subprocess
cmd=['ls','-l']
subprocess.call(cmd)
subprocess.call('cat /etc/passwd',shell=True)
2. C中使用#include 庫,下面是我寫的一個調用系統命令的函數。
使用popen,這個好處就是既能得到返回值也能得到輸出,我將調用以及返回值判斷封裝了一下,便於平時使用
#include
int execute_cmd(const char *cmdstr, char * retstr, int len)
{
FILE *fpin=NULL;
if(NULL==(fpin=popen(cmdstr,"r")))
{
WRITE_LOG_EX(UL_LOG_FATAL,"execute command '%s' failed: %s",cmdstr,strerror(errno));
return 1;
}
if(NULL == fgets(retstr, len, fpin))
{
retstr = NULL;
}
return 0;
}