`

script cmd / Execute a system command

阅读更多

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

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

http://rosettacode.org/wiki/Execute_a_System_Command

 

In this task, the goal is to run either the ls (dir on Windows) system command, or the pause system command.

Contents

 [hide]

 

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

这些语言包括

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 @results = 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

 

end

分享到:
评论

相关推荐

    DBHelper方便连接数据库 DBHelper

    public static int ExecuteCommand(string sql, params SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); return cmd.ExecuteNonQuery(); } ...

    C#执行外部命令的方法

    本文实例讲述了C#执行外部命令的方法。分享给大家供大家参考。具体实现方法如下: /// ///executes a system command from inside csharp ///&lt;/summary&gt; ...public static int executeCommand(string cmd, in

    CMS.DBUtility.dll

    public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try {...

    用ASP.NET做的博客系统

    private void ExecuteCommand(OleDbCommand cmd) { cmd.Connection=m_Connection; try { m_Connection.Open(); cmd.ExecuteNonQuery(); } finally { m_Connection.Close(); } } public DataSet ...

    SQL Server弱口令利用工具1.3版

    support xp_cmdshell execute arbtriry command support sp_OACreate create Wscript.shell execute arbtriry commnad support xp_dirtree list system directroy support execute SQL Query contact me :...

    ruby selenium-client-1.2.18.gem

    11. Go to c:\seleniumrubytest where you have the ruby script and execute the command ruby googlesearch.rb. Also make sure that you have the Selenium RC server running. 12. The selenium script will get...

    java-cmd-exec:一个简单的ProcessBuilder包装器

    java-cmd-exec 一个简单的ProcessBuilder包装器 例子 公共类Md5sumCommand扩展了Command { @Override ... Command.Result result = command.execute(); System.out.println(result.code); // exit code

    memcached 1.2.6 1.2.5

    Execute the vcvars32.bat or vsvars32.bat or vsvars64.bat file from the Visual Studio directory to allow building on the command line. e.g. "C:\Program Files\Microsoft Visual Studio .NET 2003\Common7...

    Installanywhere打包javaweb项目

    -- 菜单Pre-Uninstall&gt;,按钮Add Action&gt;Execute Command&gt;Add&gt;。 Command Line:  cmd /c $USER_INSTALL_DIR$\uninstall.bat $USER_INSTALL_DIR$ 将该Execute Command移动到第一个。 选中Options中的3个选项。 放在...

    CE中文版-启点CE过NP中文.exe

    启点CE过NP中文December 24 2018:Cheat Engine 6.8.2 Released: Here's a new version for the hollidays. Mainly minor improvements and some small bugfixes, but also a new 'ultimap like' ...Added a system...

    PrintSpoofer:Windows 10和Server 2019上的滥用模拟特权

    打印喷水器 通过在Windows 10和Server 2016/2019上滥用SeImpersonatePrivilege... Spooler service to get a SYSTEM token and then run a custom command with CreateProcessAsUser() Arguments: -c &lt;CMD&gt; Execute th

    8-07-14_MegaCLI for linux_windows

    SCGCQ00445356 (CSET) - Megacli crashes after invoking any command in SGI system with one 9280-8e and 2 quad port qlogic FC cards. SCGCQ00452383 (CSET) - New version MegaCli did not show iBBU06 over ...

    微软内部资料-SQL性能优化3

    After a transaction commits, its effects will persist even if there are system failures. Consistency and isolation are the most important in describing SQL Server’s locking model. It is up to the ...

    Command-System:基于Minecraft 1.8.9的Bukkit命令系统

    final Command cmd = CommandManager.findCommand(message); if (cmd.getExecutor() != null){ cmd.getExecutor().execute(this, CommandManager.getArgs(message)); } } else { this.sendQueue....

    LCTF软件备份VariSpec™ Liquid Crystal Tunable Filters

    b) n/a ?initial releaseDescription This package provides a set of functions to control the VariSpec filter, which may be called from C or C++ programs. It incorporates all aspects of the filter ...

    jclazz-1.2.2

    It can be used both as command line tool and user application with Swing interface. * InfoJ can be used to generate information about Java class. The output includes all possible data that can be ...

    Bochs - The cross platform IA-32 (x86) emulator

    - USB printer: output file creation failure now causes a disconnect - re-implemented "options" parameter for additional options of connected devices (currently only used to set the speed reported ...

Global site tag (gtag.js) - Google Analytics