java怎么调用linux的命令?怎么输入一条命令让linuxpython 调用终端命令运行,然后获得返回的文本?

java使用Runtime.exec执行linux命令
具有使用Run.ec对本地程序调用进行重定向的能力,但是用重定向或者管道进行调用将会出错。解决这一问题的办法是通过命令shell运行命令。在Java中调用本地程序会破坏平台独立性规则,但是经常需要这么做才行。
  以下是一个简单类的范例,展示了在Unix下运行命令的情形:
  import java.io.BufferedInputS
  import java.io.IOE
  public class ExecLs {
   ic public vo main(String[] args) {
   String cmd = "ls"
   try {
   Process ps = Runtime.getRuntime().exec(cmds);
   System.out.print(loadStream(ps.getInputStream()));
   System.err.print(loadStream(ps.getErrorStream()));
   } ch(IOException ioe) {
   ioe.printStackTrace();
   // read an input-stream into a String
   static String loadStream(InputStream in) throws IOException
   int ptr = 0;
   in = new BufferedInputStream(in);
   StringBuffer buffer = new StringBuffer();
   while( (ptr = in.read()) != -1 ) {
   buffer.append((char)ptr);
   return buffer.toString();
  上述代码中重要的部分是exec方法和命令字符串ls。本程序将输出运行目录下的列表细节。
  那么,如果你想重定向这些细节内容到文件该怎么办?这一命令行的输入应该写成ls &
FILE,但是当你将cmd变量改变成这样的话,运行就会出错,如下:
  /bin/ls: &: No ch
or directory
  /bin/ls: FILE: No such file or directory
  出错的原因在于额外的参数被直接传送到了ls命令而不是送到实际的命令行。解决这一问题的办法是将cmd串弄成一个字符串数组,并且将你想运行的程序传送到命令shell。
  因此,将cmd行改成下面的样子:
   String[] cmd = { "sh", "-c", "ls & FILE" };
  你将得到一个名为FILE的文件,里面是目录列表。-c参数是告诉它读取随后的字符串,而最后的参数是你要运行的脚本。
  在这种情况下,管道也运行良好,所以你可以把命令改成下面的方式:
  String[] cmd = { "/bin/sh", "-c", "/bin/ls |
d & FILE" };
  这种形式将给你一个名为FILE的文件,里面是ls条目中包含d的条目。给出sh和ls的全路径有利于提供你的程序的安全性。
  虽然使用Runtime.exec不是创建独立于平台的Java的最佳方式,但是有些时候是必要的。使用这种重定向技术有助于走出Runtime.exec的限制。
exec的必须是可执行的程序,如果是命令行的命令则还需另外处理
在windows中process = runtime.exec(new String[] { "cmd.exe","/C",
在linux中process = runtime.exec(new String[] { "/bin/sh","-c", "echo
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。Python执行Linux系统命令的4种方法
投稿:junjie
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Python执行Linux系统命令的4种方法,即在Python脚本中调用Shell命令,需要的朋友可以参考下
(1) os.system
仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
system(command) -& exit_status
Execute the command (a string) in a subshell.
如果再命令行下执行,结果直接打印出来
&&& os.system('ls')
.CHM&& bash&&&&& document&&& media&&&&& py-django&& video
11.wmv&&&&&&&&&&& books&&&& downloads&& Pictures& python
all-&&&&& Desktop&& Examples&&& project&&& tools
(2) os.popen
该方法不但执行命令还返回执行后的信息对象
popen(command [, mode='r' [, bufsize]]) -& pipe
Open a pipe to/from a command returning a file object.
&&&tmp = os.popen('ls *.py').readlines()
['dump_db_pickle.py ',
'dump_db_pickle_recs.py ',
'dump_db_shelve.py ',
'initdata.py ',
'__init__.py ',
'make_db_pickle.py ',
'make_db_pickle_recs.py ',
'make_db_shelve.py ',
'peopleinteract_query.py ',
'reader.py ',
'testargv.py ',
'teststreams.py ',
'update_db_pickle.py ',
'writer.py ']
好处在于:将返回的结果赋于一变量,便于程序的处理。
(3)& 使用模块 subprocess
&&& import subprocess
&&& subprocess.call(["cmd", "arg1", "arg2"],shell=True)
获取返回和输出:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
&&& print line,
retval = p.wait()
(4)& 使用模块 commands
&&& import commands
&&& dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
&&& commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
&&& commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')
注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:
Traceback (most recent call last):
& File "./test1.py", line 56, inmain()
& File "./test1.py", line 45, in main
&&& fax.sendFax()
& File "./mailfax/Fax.py", line 13, in sendFax
&&& os.popen(cmd)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128)
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(29611)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'java程序中调用linux命令',
blogAbstract:'1.Java调用shell&&Java语言以其跨平台性和简易性而著称,在Java里面的lang包里(java.lang.Runtime)提供了一个允许Java程序与该程序所运行的环境交互的接口,这就是Runtime类,在Runtime类里提供了获取当前运行环境的接口。其中的exec函数返回一个执行shell命令的子进程。exec函数的具体实现形式有以下几种:public Process exec(String command) throws IOExceptionpublic Process exec(String command,String[] envp) throwsIOExceptionpublic Process exec(String command,String[] envp,File dir) throws',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:0,
publishTime:2,
permalink:'blog/static/',
commentCount:1,
mainCommentCount:1,
recommendCount:1,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}

我要回帖

更多关于 mac命令行终端 的文章

 

随机推荐