24 种语言执行外部命令的方法

jopen 12年前

在这个例子中展示用不同语言调用外部命令的方法。觉得这个挺有意思,转来给大家看看,也许某一天你会觉得有用。

这些语言包括

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

 

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

Ada

with Interfaces.C; use Interfaces.C;      procedure Execute_System is       function Sys (Arg : Char_Array) return Integer;       pragma Import(C, Sys, "system");       Ret_Val : Integer;    begin       Ret_Val := Sys(To_C("ls"));    end Execute_System;

AppleScript

do shell script "ls" without altering line endings

C

支持版本 gcc version 4.0.1

平台: BSD

#include <stdlib.h>    int main()  {      system("ls");  }

C++

支持版本: Visual C++ version 2005

system("pause");

C#

支持版本: MCS version 1.2.3.1

using System;     class Execute {      static void Main() {          System.Diagnostics.Process proc = new System.Diagnostics.Process();          proc.EnableRaisingEvents=false;          proc.StartInfo.FileName="ls";          proc.Start();     }    }

E

def ls := makeCommand("ls")    ls("-l")         def [results, _, _] := ls.exec(["-l"])    when (results) -> {      def [exitCode, out, err] := results      print(out)    } catch problem {      print(`failed to execute ls: $problem`)    }

Forth

支持版本: gforth version 0.6.2

s" ls" system

Haskell

支持版本: GHCi version 6.6

import System.Cmd    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

import java.io.IOException;  import java.io.InputStream;    public class MainEntry {        public static void main(String[] args) {          executeCmd("ls -oa");      }        private static void executeCmd(String string) {            InputStream pipedOut = null;            try {              Process aProcess = Runtime.getRuntime().exec(string);                aProcess.waitFor();              pipedOut = aProcess.getInputStream();              byte buffer[] = new byte[2048];              int read = pipedOut.read(buffer);                // Replace following code with your intends processing tools              while(read >= 0) {                  System.out.write(buffer, 0, read);                                 read = pipedOut.read(buffer);              }          } catch (IOException e) {              e.printStackTrace();          } catch (InterruptedException ie) {              ie.printStackTrace();          } finally {              if(pipedOut != null) {                  try {                      pipedOut.close();                  } catch (IOException e) {                  }              }          }      }  }

正确的方法使用进程提供的线程去读取InputStream

import java.io.IOException;    import java.io.InputStream;         public class MainEntry {        public static void main(String[] args) {            // the command to execute            executeCmd("ls -oa");        }             private static void executeCmd(String string) {            InputStream pipedOut = null;            try {                Process aProcess = Runtime.getRuntime().exec(string);                     // These two thread shall stop by themself when the process end                Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream()));                Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream()));                                pipeThread.start();                errorThread.start();                                aProcess.waitFor();            } catch (IOException e) {                e.printStackTrace();            } catch (InterruptedException ie) {                ie.printStackTrace();            }        }    }              class StreamGobber implements Runnable {             private InputStream Pipe;             public StreamGobber(InputStream pipe) {            if(pipe == null) {                throw new NullPointerException("bad pipe");            }            Pipe = pipe;        }             public void run() {            try {                byte buffer[] = new byte[2048];                     int read = Pipe.read(buffer);                while(read >= 0) {                    System.out.write(buffer, 0, read);                         read = Pipe.read(buffer);                }            } catch (IOException e) {                e.printStackTrace();            } finally {                if(Pipe != null) {                    try {                        Pipe.close();                    } catch (IOException e) {                    }                }            }        }    }

Logo

支持版本: UCB Logo

SHELL命令返回列表:

print first butfirst shell [ls -a]   ; ..

MAXScript

dosCommand "pause"

Objective-C

支持版本:苹果公司的GCC version 4.0.1

void runls()  {      [[NSTask launchedTaskWithLaunchPath:@"/bin/ls"          arguments:[NSArray array]] waitUntilExit];  }

如果你希望调用系统命令,先执行shell

void runSystemCommand(NSString *cmd)  {      [[NSTask launchedTaskWithLaunchPath:@"/bin/sh"          arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]]          waitUntilExit];  }

同样可以使用上面的C语言调用方法。

OCaml

Sys.command "ls"

Perl


my @result = qx(ls);  # runs command and returns its STDOUT    my @results = `ls`;  # dito, alternative syntax    system "ls";  # runs command and returns its exit status    print `ls`;  #The same, but with back quotes    exec "ls";  # replace current process with another

另外可以参阅 http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC http://perldoc.perl.org/IPC/Open3.html

PHP

首行执行命令,第二行显示输出:

@exec($command,$output);    echo nl2br($output);

注意这里的‘@’防止错误消息的显示,‘nl2br’ ‘\n’转换为HTML‘br’ 

Pop11

sysobey(’ls’);

Python

支持版本: Python version 2.5

 import os   code = os.system(’ls’) # Just execute the command, return a success/fail code   output = os.popen(’ls’).read() # If you want to get the output data

或者

支持版本: Python version 2.4 (及以上版本)

 import subprocess   output = subprocess.Popen(’ls’, shell=True, stdout=subprocess.PIPE).stdout   print output.read()

后者是比较好的方法。

或者

支持版本: Python version 2.2 (及以上版本)

 import commands   stat, out = commands.getstatusoutput(’ls’)   if not stat:      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