Get system command output: Difference between revisions
Added XPL0 example.
No edit summary |
(Added XPL0 example.) |
||
(9 intermediate revisions by 7 users not shown) | |||
Line 10:
{{works with|Commodore 64}}
Uses the system call <code>$FFED</code> which returns the screen dimensions (measured in 8x8 pixel squares).
<
;returns screen width in X and screen height in Y
dex ;subtract 1. This is more useful for comparisons.
dey ;subtract 1. This is more useful for comparisons.
stx $20 ;store in zero page ram
sty $21 ;store in zero page ram</
Line 21:
{{works with|NEOGEO MVS}}
This program uses the system command that retrieves the current time, which is used to seed a random number generator. All labels are either routines, macros, or memory locations as appropriate. Code is called during the game's vBlank routine.
<
;run this during vblank for best results.
JSR SYS_READ_CALENDAR
Line 41:
SwapRNGifEven:
MOVE.L D0,RNGout_32
rts</
The following macro is used in the above routine:
<
;\1 must be a data register.
;copies the lowest byte to all 4 bytes.
Line 53:
SWAP \1
popWord \1
endm</
=={{header|Ada}}==
{{works with|GNAT}}
<
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect; use GNAT.Expect;
Line 95:
end loop;
end System_Command;</
=={{header|Aime}}==
<
{{Out}}
<pre>-- 72 --</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
/* JAMBO language - a flavour of Hopper */
#include <jambo.h>
Line 110:
Set( sys ) Prnl
End
</syntaxhighlight>
{{out}}
<pre>
Line 117:
#include <jambo.h>
Main
sys = `cat jm/
Set( sys ) Prnl
End
Line 125:
=={{header|Applesoft BASIC}}==
A small machine language program is POKEd into memory starting at address P. The address of the program P is POKEd into the 54 and 55 zero page locations. CALL 1002 connects output to the program. The system command CATALOG is run, and all output is written to memory starting at address A. PR#0 reconnects output back to the screen. Variables are carefully declared before the first string in the array S$(0) is assigned. The most recent address of S$(0) is used to assign pointers and lengths to the array of strings. S$(C) is the last string in the array.
<
110 LET A = 24576
120 LET P = 768
Line 168:
510 POKE S + C * 3 + 2, FN H(I)
520 PRINT S$(C);
530 NEXT </
=={{header|Arturo}}==
<
{{out}}
Line 178:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
BEGIN {
Line 216:
close(command)
return ship
}</
=={{header|
==={{header|BaCon}}===
<
result$ = EXEC$("fortune")
PRINT CHOP$(result$)
PRINT "First word: " & TOKEN$(result$, 1)</
{{out}}
Line 232 ⟶ 233:
=={{header|Batch File}}==
<
@echo off
setlocal enabledelayedexpansion
Line 258 ⟶ 259:
pause>nul
</syntaxhighlight>
=={{header|Bracmat}}==
<
.sys$(str$(!arg " > temp"))&get$(temp,STR)
);</
Example:
<syntaxhighlight lang
'''Output'''
<pre>Changelog
Line 289 ⟶ 290:
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 326 ⟶ 327:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
namespace GetSystemCommandOutput {
Line 348 ⟶ 349:
}
}
}</
=={{header|C++}}==
<
#include <iostream>
Line 368 ⟶ 369:
int main() {
std::cout << execute("whoami") << '\n';
}</
===Boost alternative===
{{libheader|Boost}}
<
#include <string>
#include <vector>
Line 405 ⟶ 406:
}
return EXIT_SUCCESS;
}</
=={{header|Clojure}}==
sh returns a map of exit code, stdout, and stderr from the command:
<
(sh "echo" "Hello")</
{{out}}
Line 417 ⟶ 418:
=={{header|Common Lisp}}==
{{libheader|trivial-shell}}
<
{{out}}
Line 429 ⟶ 430:
the :output keyword. We can then read from the stream:
<
(sb-ext:run-program "mplayer" (list "/path/to/groovy/tune")
:search t :output :stream :wait nil))
(read-line (sb-ext:process-output *my-proc*) nil)</
{{libheader|uiop}}
A bit more general, using [https://github.com/fare/asdf uiop] and grabbing output as a string:
<
=={{header|D}}==
<
import std.stdio;
Line 450 ⟶ 451:
writeln("Failed to execute command, status=", cmd.status);
}
}</
{{out}}
Line 456 ⟶ 457:
=={{header|F_Sharp|F#}}==
<
// System Command Output. Nigel Galloway: October 6th., 2020
let n=new System.Diagnostics.Process(StartInfo=System.Diagnostics.ProcessStartInfo(RedirectStandardOutput=true,RedirectStandardError=true,UseShellExecute=false,
Line 463 ⟶ 464:
printfn "%s" ((n.StandardOutput).ReadToEnd())
n.Close()
</syntaxhighlight>
{{out}}
<pre style="height:64ex;overflow:scroll">
Line 629 ⟶ 630:
=={{header|Factor}}==
<code>with-process-reader</code> is a combinator that encapsulates reading the output of a system command. It also throws an error along with the appropriate exit status in the event of failure.
<
"echo hello" utf8 [ contents ] with-process-reader .</
{{out}}
<pre>
Line 638 ⟶ 639:
=={{header|Forth}}==
Using Gforth 0.7.9
<
\ read via pipe into buffer
create buffer 266 allot
Line 647 ⟶ 648:
buffer swap type \ output is the same like above
</syntaxhighlight>
{{out}}
<pre>
Line 658 ⟶ 659:
=={{header|FreeBASIC}}==
<
'capture the output of the 'dir' command and print it to a text file
Line 673 ⟶ 674:
Close #2
Close #1
End</
=={{header|FutureBasic}}==
Simple system commands can be run in FB's open "UNIX" function. However, more common are functions such as this example which uses a notification observer to
<
include "NSLog.incl"
local fn ObserverOne( ref as NotificationRef )
FileHandleRef fh = fn NotificationObject( ref )
CFDataRef dta = fn FileHandleAvailableData( fh )
if ( fn DataLength( dta ) > 0 )
CFStringRef string = fn StringWithData( dta, NSUTF8StringEncoding )
NSLog( @"%@", string )
FileHandleWaitForDataInBackgroundAndNotify( fh )
else
NotificationCenterRemoveObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification )
end if
end fn
local fn RunCommand( cmdStr as CFStringRef )
TaskRef task = fn TaskInit▼
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/sh" ) )▼
▲TaskRef task = fn TaskInit
CFArrayRef arguments = fn ArrayWithObjects( @"-c", cmdStr, NULL )▼
▲TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/sh" ) )
TaskSetArguments( task, arguments )▼
▲CFArrayRef arguments = fn ArrayWithObjects( @"-c", cmdStr, NULL )
PipeRef p = fn PipeInit▼
▲TaskSetArguments( task, arguments )
TaskSetStandardOutput( task, p )▼
▲PipeRef p = fn PipeInit
FileHandleRef fh = fn PipeFileHandleForReading( p )▼
▲TaskSetStandardOutput( task, p )
NotificationCenterAddObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification, (FileHandleRef)fh )▼
▲FileHandleRef fh = fn PipeFileHandleForReading( p )
fn TaskLaunch( task, NULL )▼
▲NotificationCenterAddObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification, (FileHandleRef)fh )
FileHandleWaitForDataInBackgroundAndNotify( fh )▼
▲fn TaskLaunch( task, NULL )
▲FileHandleWaitForDataInBackgroundAndNotify( fh )
end fn
Line 711:
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
Line 744 ⟶ 745:
Mac OS X June 3, 2004 Mac OS X
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=d595094b5bc9c3abb17808b2b00938f9 Click this link to run this code]'''
<
Dim sStore As String
Line 759 ⟶ 754:
Print sStore
End</
Output:
Line 780 ⟶ 775:
=={{header|Genie}}==
<
/*
Get system command output, in Genie
Line 798 ⟶ 793:
print standard_output
except e : SpawnError
stderr.printf("%s\n", e.message)</
{{out}}
Line 809 ⟶ 804:
=={{header|Go}}==
<
import (
Line 823 ⟶ 818:
}
fmt.Print(string(output))
}</
=={{header|Haskell}}==
Line 829 ⟶ 824:
{{libheader|process}}
<
-- stack --resolver lts-8.15 --install-ghc runghc --package process
Line 840 ⟶ 835:
-- print each line in reverse
mapM_ (putStrLn . reverse) results</
=={{header|Icon}} and {{header|Unicon}}==
<
# piped.icn, Get system command output
#
Line 865 ⟶ 860:
close(p)
end</
{{out}}
Line 873 ⟶ 868:
=={{header|IS-BASIC}}==
<
110 SET DEFAULT CHANNEL 1
120 EXT "dir"
130 CLOSE #1
140 SET DEFAULT CHANNEL 0</
=={{header|J}}==
Line 883 ⟶ 878:
We will box the result of uname -imp on a linux system, to show that we have captured the command output in J:
<
<shell 'uname -imp'
┌─────────────────────┐
│x86_64 x86_64 x86_64 │
└─────────────────────┘</
Caution: I have sometimes seen some versions of linux refuse to execute subshells after a few hundred thousand shell commands (the exec system call fails). I've not found any satisfying documentation on why this happens, but I strongly suspect kernel memory fragmentation (the examples where this happened were also using a lot of memory to accumulate results and it happened much more frequently
(I've seen other problems on windows and osx - I am only singling out linux here because it is the most convenient for command line and system command use.)
Line 895 ⟶ 890:
=={{header|Java}}==
{{works with|Java|7}}
<
import java.util.*;
Line 913 ⟶ 908:
}
}
}</
Output:
Line 936 ⟶ 931:
=={{header|Jsish}}==
<
puts(commandOutput.data);</
The jsish ''exec'' command (like many jsish commands) accepts an optional option object, details available with interactive help:
Line 971 ⟶ 966:
In a single string:
<
In multiple lines:
<
=={{header|Kotlin}}==
<
import java.util.Scanner
Line 987 ⟶ 982:
println(sc.nextLine())
sc.close()
}</
{{out}}
Line 997 ⟶ 992:
The library from lil.c does not include a system command, but main.c for the lil shell does.
<
{{out}}
Line 1,058 ⟶ 1,053:
=={{header|Lingo}}==
{{libheader|Shell Xtra}}
<
put sx.shell_cmd("cd C:\dev\lsw\lib & dir")
Line 1,070 ⟶ 1,065:
23.06.2016 18:22 <DIR> base64
23.06.2016 18:21 <DIR> base9
<snip>"</
=={{header|Lua}}==
<
print(output:read("*all"))</
{{out}}
<pre>Hurrah!</pre>
Line 1,080 ⟶ 1,075:
=={{header|M2000 Interpreter}}==
Make a UTF-16LE txt.out from dir using a new cmd with /U
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Dos "cd "+quote$(Dir$) +" & cmd /U /C dir *.txt >txt.out";
Line 1,093 ⟶ 1,088:
}
Checkit
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre><|"ExitCode" -> 0, "StandardOutput" -> "Wed Oct 4 14:01:01 BST 2017", "StandardError" -> ""|></pre>
=={{header|Neko}}==
<
var process_run = $loader.loadprim("std@process_run", 2);
var process_stdout_read = $loader.loadprim("std@process_stdout_read", 4);
Line 1,158 ⟶ 1,153:
/* Get the exit status */
var ps = process_exit(proc);
sys_exit(ps);</
{{out}}
Line 1,176 ⟶ 1,171:
=={{header|Nim}}==
<
# Output string and error code
Line 1,189 ⟶ 1,184:
echo "Output: " & lsStr
</syntaxhighlight>
=={{header|Objeck}}==
<
function : Main(args : String[]) ~ Nil {
output := System.Runtime->CommandOutput("ls -l");
Line 1,200 ⟶ 1,195:
}
}
</syntaxhighlight>
=={{header|ooRexx}}==
===version 1===
<
trace normal
Line 1,230 ⟶ 1,225:
/* Exit with the system command's return code. */
exit ls_rc</
===version 2===
<
cmd '| rxqueue'
Say 'Output of "'cmd'"'
Line 1,239 ⟶ 1,234:
parse pull text
Say text
End </
{{out}}
<pre>Output of "dir tu*.rex /od"
Line 1,253 ⟶ 1,248:
0 Verzeichnis(se), 3.357.933.568 Bytes frei </pre>
===version 3===
<
cmd='dir t*.rex /od'
cmd '>'dir
Line 1,262 ⟶ 1,257:
Say linein(dir)
End
Call lineout oid</
{{out}}
<pre>identical to version 2's output</pre>
=={{header|PARI/GP}}==
<
=={{header|Perl}}==
Uses the qx{} construct (which is a synonym for backticks, e.g. `command`) to execute a given command and redirect its output.
A (somewhat contrived*) example, capturing only STDOUT:
<
for (@directories) {
chomp;
...; # Operate on directories
}</
* Perl's opendir function should be used in preference to parsing ls--it's safer, faster, and more portable.
Perl also honors shell redirections:
<
my @output_and_errors = qx/$command 2>&1/ or die "Couldn't execute command\n";</
qx// is implemented internally with the built-in function readpipe, which can be invoked directly as readpipe EXPR (where EXPR is some command) and assigned to scalars or lists just like qx/command/ or `command`.
The open command can also be used to open pipes using the -| mode:
<
my $enc = ':encoding(UTF-8)';
my $child_pid = open(my $pipe, "-|$enc", 'ls');
Line 1,291 ⟶ 1,286:
# Print all files whose names are all lowercase
print if m/[^A-Z]+/;
}</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- system_exec, file i/o</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"hostname.txt"</span><span style="color: #0000FF;">,</span>
Line 1,302 ⟶ 1,297:
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">host</span>
<!--</
{{out}}
<pre>
Line 1,310 ⟶ 1,305:
=={{header|Phixmonti}}==
<
"hostname > " hname chain cmd
hname "r" fopen
dup fgets print fclose
"del " hname chain cmd</
=={{header|PicoLisp}}==
<
-> "aarch64 Android"</
=={{header|PowerShell}}==
Capture system disk label information as an array of strings:
<syntaxhighlight lang="powershell">
[string[]]$volume = cmd /c vol
$volume
</syntaxhighlight>
{{Out}}
<pre>
Line 1,334 ⟶ 1,329:
=={{header|PureBasic}}==
<
rp=RunProgram("ls", "-l", "",#PB_Program_Open|#PB_Program_Read)
While ProgramRunning(rp)
Line 1,345 ⟶ 1,340:
Input()
EndIf
</syntaxhighlight>
=={{header|Python}}==
<
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
Line 1,376 ⟶ 1,371:
9 Dir(s) 46,326,947,840 bytes free
>>> # Ref: https://docs.python.org/3/library/subprocess.html</
=={{header|Quackery}}==
Line 1,402 ⟶ 1,397:
=={{header|R}}==
<
system("wc -l /etc/passwd /etc/group", intern = TRUE)
</syntaxhighlight>
{{out}}
<pre>
Line 1,413 ⟶ 1,408:
We use <code>#lang racket/base</code> to show which module system is in. It would be imported anyway if we use the larger <code>#lang racket</code>.
This demonstrates one function: <code>system</system></code>. It is the simplest of a family of commands in the <code>racket/system</code> collection.
See [http://docs.racket-lang.org/reference/subprocess.html?q=system#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%29%29 documentation for <code>system</code> and friends].
<
(require racket/system
Line 1,444 ⟶ 1,439:
(system "echo -n foo; echo bar 1>&2"))))
(values system-rv (get-output-string out-str-port) (get-output-string err-str-port)))
=> (values #t "foo" "bar\n"))</
{{out}}
Line 1,464 ⟶ 1,459:
If you don't want to execute it in shell (and you probably don't), then use this:
<syntaxhighlight lang="raku"
Unfortunately, it is very long to type, but that is the only way to pass your variables as arguments safely.
You might be tempted to start using shell when you have to pipe something, but even in that case there is no need to do so. See this code:
<syntaxhighlight lang="raku"
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.slurp-rest;</
See [https://docs.raku.org/type/Proc docs] for more info.
If you really want to run something in shell and you understand potential security problems, then you can use <code>qx//</code> (interpolates environment variables) or <code>qqx//</code> (interpolates normally). See [https://docs.raku.org/language/quoting the docs for more info].
<syntaxhighlight lang="raku"
{{out}}
<pre>Find_URI_in_text.p6 History_variables.p6 K-d_tree.pl
Line 1,483 ⟶ 1,478:
=={{header|REXX}}==
{{works with|Regina REXX}}
<
parse arg xxxCmd /*obtain the (system) command from CL.*/
trace off /*suppress REXX error msgs for fails. */
Line 1,493 ⟶ 1,488:
say strip(@.#, 'T') /*display one line at a time──►terminal*/
end /*#*/ /* [↑] displays all the output. */
exit 0 /*stick a fork in it, we're all done. */</
{{out|output|text= from the executed command (under Windows/XP): <tt> dir g:sub*.2*</tt>}}
<pre>
Line 1,515 ⟶ 1,510:
=={{header|Ring}}==
<
system("dir C:\Ring\doc")
</syntaxhighlight>
Output:
<pre>
Line 1,535 ⟶ 1,530:
=={{header|Ruby}}==
Many options, google exec or system or %x. Demonstrating backticks:
<
arr = `ls`.lines</
=={{header|Run BASIC}}==
<
print a$ ' prints the directory
</syntaxhighlight>
=={{header|Rust}}==
<
use std::io::{Write, self};
Line 1,554 ⟶ 1,549:
io::stdout().write(&output.stdout);
}</
=={{header|Scala}}==
<
val command = "cmd /c echo Time at %DATE% %TIME%"
val p = Runtime.getRuntime.exec(command)
val sc = Source.fromInputStream(p.getInputStream)
println(sc.mkString)</
=={{header|Sidef}}==
Using backticks:
<
var lines = `ls`.lines # `lines` is an array</
Using pipes:
<
var pipe_h = pipe.open_r # open the pipe for reading
var lines = [] # will store the lines of the output
pipe_h.each { |line| lines << line }</
=={{header|Stata}}==
Redirect the output to a temporary file, then read its contents into a result macro r(out).
<
tempfile f
tempname m
Line 1,592 ⟶ 1,587:
return local out "`s'"
}
end</
'''Example:'''
<
. display r(out)
auto.dta
Line 1,603 ⟶ 1,598:
. shellout python -V
. display r(out)
Python 3.6.2</
=={{header|Swift}}==
<
let process = Process()
Line 1,621 ⟶ 1,616:
let output = String.init(data: data, encoding: String.Encoding.utf8)
print(output!)</
=={{header|Standard ML}}==
<
let
val text = String.translate (fn #"\"" => "\\\""|n=>str n ) input ;
Line 1,650 ⟶ 1,645:
)
end;
</syntaxhighlight>
call
useOS "This is my text, zip it now" ;
Line 1,659 ⟶ 1,654:
=={{header|Tcl}}==
The <code>exec</code> makes this straight-forward for most commands.
<
puts "read [string length $data] bytes and [llength [split $data \n]] lines"</
There are a few exceptions, such as the <tt>DIR</tt> command on Windows, where they need to be run slightly differently due to being system shell builtins rather than executables. In that case, the <code>auto_execok</code> standard library command is used to look up how to run the command (strictly it can be used for any command — it will do path resolution, etc. — but is only necessary for system builtins).
<
By default, Tcl will use the system encoding (as reported by <code>encoding system</code>) to understand the output byte-stream as characters, and will auto-convert all the various types of newline terminators into <tt>U+00000A</tt> characters. Control over this is possible by launching the subprocess as a pipe, configuring the pipe, and then reading the pipe in its entirety.
<
set pipe [open |[list ls -l] "r"]
fconfigure $pipe -encoding iso8859-1 -translation lf
set data [read $pipe]
close $pipe</
This is usually not necessary except when dealing with binary data output.
=={{header|Ursa}}==
This program reads the output of the ifconfig command into the string stream 'output', then writes it to the screen.
<
> decl string<> arg
> append "ifconfig" arg
Line 1,712 ⟶ 1,707:
media: autoselect
status: inactive
> </
=={{header|VBScript}}==
This program implements a function that executes a DOS command and returns the output to the caller.
<
Wscript.Echo line
Next
Line 1,735 ⟶ 1,730:
'Return as a text array
ExecCmd = Split(Mid(res,2),vbLf)
End Function</
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Main()
Line 1,758 ⟶ 1,753:
End Sub
End Module</
=={{header|Wren}}==
Line 1,765 ⟶ 1,760:
However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to do it for us.
<
class Command {
foreign static output(name, param) // the code for this is provided by Go
}
System.print(Command.output("ls", "-ls"))</
which we embed in the following Go program and run it.
{{libheader|WrenGo}}
<
package main
Line 1,805 ⟶ 1,800:
func main() {
vm := wren.NewVM()
fileName := "
methodMap := wren.MethodMap{"static output(_,_)": getCommandOutput}
classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)}
Line 1,812 ⟶ 1,807:
vm.InterpretFile(fileName)
vm.Free()
}</
=={{header|XPL0}}==
Use a pipe on the command line to run this. For example: dir | syscmd
<syntaxhighlight lang "XPL0">int C;
repeat C:= ChIn(1);
if C>=^a & C<=^z then \lowercase letters to uppercase
C:= C & ~$20;
ChOut(0, C);
until C = $1A</syntaxhighlight>
=={{header|Yabasic}}==
<
// by Jjuanhdez, 06/2022
Line 1,826 ⟶ 1,830:
open("dir_output.txt") for writing as #1
print #1 system$(c$)
close #1</
=={{header|zkl}}==
From the REPL on Linux. Runs a command in the shell with stdout redirected to file, then slurps the file. A bit greasy since there isn't a way to find/generate a unique unused file name.
<
0 // date return code
zkl: File("foo.txt").read().text
Wed Aug 20 00:28:55 PDT 2014</
|