Execute a system command: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 223: Line 223:
echo nl2br($output);
echo nl2br($output);
'''Note:'''The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.
'''Note:'''The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.

==[[Pop11]]==
[[Category:Pop11]]

The sysobey function runs commans using a shell:

sysobey('ls')



==[[Python]]==
==[[Python]]==

Revision as of 02:09, 12 May 2007

Task
Execute a system command
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to run either the ls system command, or the pause 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

Compiler: GCC 4.0.1

Platform: BSD

#include <stdlib.h>

int main()
{
    system("ls");
}

C++

Compiler: Visual C++ 2005

system("pause");

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`)
}

Haskell

Interpreter: GHCi 6.6

import System.Cmd

main = system "ls"

IDL

 $ls

Will execute "ls" with output to the screen.

 spawn,"ls",result

will execute it and store the result in the string array "result".

 spawn,"ls",unit=unit

will execute it asynchronously and direct any output from it into the LUN "unit" from whence it can be read at any (later) time.

Java

Compiler: JDK 1.4 and up There is two way to run system commands. The simple way, which have the inconvenience to hang the JVM (I would be interested in some kind of reason).

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) {
                }
            }
        }
    }
    
    
}

And the right way, which use threading to read the inputstream given by the process.

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();
        }
    }
}

//Replace the following thread with your intends reader
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) {
                }
            }
        }
    }
}

Objective-C

Compiler: GCC 4.0.1 (apple)

NSTask runs an external process with explicit path and arguments.

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

If you need to run a system command, invoke the shell:

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

Or use the C method above.

Perl

Interpreter: Perl

Note the use of grave quotes (or back ticks) instead of "normal" single quotes or the qx() command.

 my $results = `ls`;
 my $results = qx(ls);

Back ticks as above returns the results, system as below does not.

 system "ls";

PHP

The first line execute the command and the second line display the output :

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

Note:The '@' is here to prevent error messages to be displayed, 'nl2br' translate '\n' chars to 'br' in HTML.

Pop11

The sysobey function runs commans using a shell:

 sysobey('ls')


Python

Interpreter: Python 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

or

Interpreter:Python 2.4 (and above)

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

Note: The latter is the preferred method for calling external processes, although cumbersome, it gives you finer control over the process.

or

Interpreter:Python 2.2 (and above)

 import commands
 stat, out = commands.getstatusoutput('ls')
 if not stat:
    print out

Ruby

string = `ls`

Tcl

  puts [exec ls]

This page uses "ls" as the primary example. For what it's worth, Tcl has built-in primitives for retrieving lists of files so one would rarely ever directly exec an ls command.

It is also possible to execute a system command by "open"ing it through a pipe from whence any output of the command can be read at any (later) time. For example:

 set io [open "|ls" r]

would execute "ls" and pipe the result into the unit "io". From there one could receive it either line by line like this:

 set nextline [gets $io]

or read the whole shebang in a fell swoop:

 set lsoutput [read $io]

If the command is opened "rw", it is even possible to send it user input through the same handle.

UNIX Shell

UNIX shells are designed to run system commands as a default operation.

ls

If one wants to capture the command's standard output:

CAPTUREDOUTPUT=$(ls)

In C-Shell this can be achieved by

set MYCMDOUTPUT = `ls`
echo $MYCMDOUTPUT 

Where as in Korn Shell it becomes:

 MYCMDOUTPUT=`ls`
 echo $MYCMDOUTPUT