24 种语言执行外部命令的方法
南宁达内:24 种语言执行外部命令的方法
在这个例子中展示用不同语言调用外部命令的方法。觉得这个挺有意思,转来给大家看看,也许某你会觉得有用。
这些语言包括
Ada
AppleScript
C
C++
C#
E
Forth
Haskell
IDL
J
Java
Logo
MAXScript
Objective-C
OCaml
Perl
PHP
Pop11
Python
Raven
Ruby
Tcl
Toka
UNIX Shell
原文在
Ada
01 with Interfaces.C; use Interfaces.C;
02
03
04 procedure Execute_System is
05
06 function Sys (Arg : Char_Array) return Integer;
07
08 pragma Import(C, Sys, "system");
09
10 Ret_Val : Integer;
11
12 begin
13
14 Ret_Val := Sys(To_C("ls"));
15
16 end Execute_System;
AppleScript
1 do shell script "ls" without altering line endings
C
支持版本 gcc version 4.0.1
平台: BSD
1 #include
2
3 int main()
4 {
5 system("ls");
6 }
C++
支持版本: Visual C++ version 2005
1 system("pause");
C#
支持版本: MCS version 1.2.3.1
01 using System;
02
03 class Execute {
04 static void Main() {
05 System.Diagnostics.Process proc = new System.Diagnostics.Process();
06 proc.EnableRaisingEvents=false;
07 proc.StartInfo.FileName="ls";
08 proc.Start();
09 }
10
11 }
E
01 def ls := makeCommand("ls")
02
03 ls("-l")
04
05
06
07 def [results, _, _] := ls.exec(["-l"])
08
09 when (results) -> {
10
11 def [exitCode, out, err] := results
12
13 print(out)
14
15 } catch problem {
16
17 print(`failed to execute ls: $problem`)
18
19 }
Forth
支持版本: gforth version 0.6.2
1 s" ls" system
Haskell
支持版本: GHCi version 6.6
1 import System.Cmd
2
3 main = system "ls"
IDL
带屏幕输出的 "ls" :
$ls
将输出保存到数组"result":
spawn,"ls",result
异步执行,将输出转到LUN "unit",以便在以后读取:
spawn,"ls",unit=unit
J
J语言系统命令界面由标准的"task"脚本提供:
load’task’
NB. Execute a command and wait for it to complete
shell ‘dir’
NB. Execute a command but don’t wait for it to complete
fork ‘notepad’
NB. Execute a command and capture its stdout
stdout =: shell ‘dir’
NB. Execute a command, provide it with stdin,
NB. and capture its stdout
stdin =: ‘blahblahblah’
stdout =: stdin spawn ‘grep blah’
Java
支持版本: Java version 1.4+
有两种执行系统命令的方法,简单的方法会挂起JVM
01 import java.io.IOException;
02 import java.io.InputStream;
03
04 public class MainEntry {
05
06 public static void main(String[] args) {
07 executeCmd("ls -oa");
08 }
09
10 private static void executeCmd(String string) {
11
12 InputStream pipedOut = null;
13
14 try {
15 Process aProcess = Runtime.getRuntime().exec(string);
16
17 aProcess.waitFor();
18 pipedOut = aProcess.getInputStream();
19 byte buffer[] = new byte[2048];
20 int read = pipedOut.read(buffer);
21
22 // Replace following code with your intends processing tools
23 while(read >= 0) {
24 System.out.write(buffer, 0, read);
25 read = pipedOut.read(buffer);
26 }
27 } catch (IOException e) {
28 e.printStackTrace();
29 } catch (InterruptedException ie) {
30 ie.printStackTrace();
31 } finally {
32 if(pipedOut != null) {
33 try {
34 pipedOut.close();
35 } catch (IOException e) {
36 }
37 }
38 }
39 }
40 }
正确的方法使用进程提供的线程去读取InputStream。
001 import java.io.IOException;
002
003 import java.io.InputStream;
004
005
006
007 public class MainEntry {
008
009 public static void main(String[] args) {
010
011 // the command to execute
012
013 executeCmd("ls -oa");
014
015 }
016
017
018
019 private static void executeCmd(String string) {
020
021 InputStream pipedOut = null;
022
023 try {
024
025 Process aProcess = Runtime.getRuntime().exec(string);
026
027
028
029 // These two thread shall stop by themself when the process end
030
031 Thread pipeThread = new Thread(newStreamGobber(aProcess.getInputStream()));
032
033 Thread errorThread = new Thread(newStreamGobber(aProcess.getErrorStream()));
034
035
036
037 pipeThread.start();
038
039 errorThread.start();
040
041
042
043 aProcess.waitFor();
044
045 } catch (IOException e) {
046
047 e.printStackTrace();
048
049 } catch (InterruptedException ie) {
050
051 ie.printStackTrace();
052
053 }
054
055 }
056
057 }
058
059
060
061
062
063 class StreamGobber implements Runnable {
064
065
066
067 private InputStream Pipe;
068
069
070
071 public StreamGobber(InputStream pipe) {
072
073 if(pipe == null) {
074
075 throw new NullPointerException("bad pipe");
076
077 }
078
079 Pipe = pipe;
080
081 }
082
083
084
085 public void run() {
086
087 try {
088
089 byte buffer[] = new byte[2048];
090
091
092
093 int read = Pipe.read(buffer);
094
095 while(read >= 0) {
096
097 System.out.write(buffer, 0, read);
098
099
100
101 read = Pipe.read(buffer);
102
103 }
104
105 } catch (IOException e) {
106
107 e.printStackTrace();
108
109 } finally {
110
111 if(Pipe != null) {
112
113 try {
114
115 Pipe.close();
116
117 } catch (IOException e) {
118
119 }
120
121 }
122
123 }
124
125 }
126
127 }
Logo
支持版本: UCB Logo
SHELL命令返回列表:
1 print first butfirst shell [ls -a] ; ..
MAXScript
dosCommand "pause"
Objective-C
支持版本:苹果公司的GCC version 4.0.1
1 void runls()
2 {
3 [[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
4 arguments:[NSArray array]] waitUntilExit];
5 }
如果你希望调用系统命令,先执行shell:
1 void runSystemCommand(NSString *cmd)
2 {
3 [[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
4 arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]]
5 waitUntilExit];
6 }
同样可以使用上面的C语言调用方法。
OCaml
Sys.command "ls"
Perl
01 my @result = qx(ls);
02 # runs command and returns its STDOUT
03
04 my @results = `ls`;
05 # dito, alternative syntax
06
07 system "ls";
08 # runs command and returns its exit status
09
10 print `ls`;
11 #The same, but with back quotes
12
13 exec "ls";
14 # replace current process with another
另外可以参阅
PHP
行执行命令,第二行显示输出:
1 @exec($command,$output);
2
3 echo nl2br($output);
注意这里的‘@’防止错误消息的显示,‘nl2br’ 将 ‘\n’转换为HTML的‘br’
Pop11
sysobey(’ls’);
Python
支持版本: Python version 2.5
1 import os
2 code = os.system(’ls’) # Just execute the command, return a success/fail code
3 output = os.popen(’ls’).read() # If you want to get the output data
或者
支持版本: Python version 2.4 (及以上版本)
1 import subprocess
2 output = subprocess.Popen(’ls’, shell=True, stdout=subprocess.PIPE).stdout
3 print output.read()
后者是比较好的方法。
或者
支持版本: Python version 2.2 (及以上版本)
1 import commands
2 stat, out = commands.getstatusoutput(’ls’)
3 if not stat:
4 print out
Raven
`ls -la` as listing
或者任何字符串
‘ls -la’ shell as listing
Ruby
string = `ls`
Tcl
puts [exec ls]
同样可以使用系统open命令。
set io [open "|ls" r]
获取结果的方法是
set nextline [gets $io]
或者
set lsoutput [read $io]
如果命令是以RW方式打开,可以用同样的方法发送用户的输入。
Toka
needs shell
" ls" system
UNIX Shell
直接调用
ls
如果希望获取标准输出
CAPTUREDOUTPUT=$(ls)
在 C-Shell 中可以这样做
set MYCMDOUTPUT = `ls`
echo $MYCMDOUTPUT
在Korn Shell 中是这样:
MYCMDOUTPUT=`ls`
echo $MYCMDOUTPUT
文中图片素材来源网络,如有侵权请联系删除网上报名
新闻资讯
更多>>-
达内就业快讯
2012-11-12
-
达内招聘
2012-11-12
-
南宁达内:才气外露 Google推安卓程
2012-11-21
-
南宁达内:PHP最近很疯狂
2012-11-21
-
南宁达内:Sina微博OAuth2框架
2012-11-21