在這個例子中展現用不一樣語言調用外部命令的方法。以爲這個挺有意思,轉來給你們看看,也許某一天你會以爲有用。html

這些語言包括java

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 Shellshell

 

原文在 http://www.rosettacode.org/wiki/Execute_a_System_Command數組

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異步

平臺: BSDide

1 #include <stdlib.h>
2  
3 int main()
4 {
5     system("ls");
6 }

C++

支持版本: Visual C++ version 2005spa

1 system("pause");

C#

支持版本: MCS version 1.2.3.1.net

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.6code

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

另外能夠參閱 http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC http://perldoc.perl.org/IPC/Open3.html

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

http://www.cocoachina.com/b/?p=171