24 種語言執行外部命令的方法

jopen 12年前發布 | 31K 次閱讀 語言

在這個例子中展示用不同語言調用外部命令的方法。覺得這個挺有意思,轉來給大家看看,也許某一天你會覺得有用。

這些語言包括

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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!