现在的位置: 首页 > 综合 > 正文

各种编译语言调用shell命令,如何得到输出结果?

2013年08月10日 ⁄ 综合 ⁄ 共 570字 ⁄ 字号 评论关闭

(1) Python //前面的文章中已经提到过了
http://blog.chinaunix.net/u/12325/showart_217175.html

两种方法,一种是且Popen.
output = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE,shell=True).commun
icate()
print output[0]
 

另外一种则可返回状态与调用的shell命令的输出结果
>>> import commands
>>> status, output = commands.getstatusoutput('ls -l')

(2) Perl //这个相比之下就简单多了
$out=`shell command`

(3) Shell
最简单的方法是这样:
    out=`shell command`
或者
    out=$(shell command)
不过要注意的是,如果shell command的输出结果为多行,而这样放进变量中的时候,默认的echo $out是不输出换行的(参看IFS相关的文档),echo "$out"就可以了。

(4) C
     #include <stdlib.h>
     int system(const char *string);

当调用system("command");的时候,执行结果是打在标准输出的。

 

抱歉!评论已关闭.