Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Get_system_command_output

View file

@ -0,0 +1,6 @@
;Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
<br><br>
;Related task
* [[Execute_a_system_command | Execute a system command]]
<br><br>

View file

@ -0,0 +1,6 @@
JSR $FFED
;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

View file

@ -0,0 +1,21 @@
doRNG:
;run this during vblank for best results.
JSR SYS_READ_CALENDAR
;gets the calendar.
;MAME uses your computer's time for this.
MOVE.L BIOS_HOUR,D0 ;D0 = HHMMSS00
LSR.L #8,D0 ;shift out the zeroes.
MOVE.L frame_timer,D1 ;this value is incremented by 1 every vBlank (i.e. just before this procedure is run)
NOT.L D1 ;flip all the bits of D1
MULS D1,D0
MULU D1,D0
MOVE.L JOYPAD1,D1 ;get the most recent button presses.
CloneByte D1 ;copy this byte to all 4 bytes of D1
EOR.L D1,D0
MOVE.L RNGout_32,D2 ;look at last time's results.
AND.B #1,D2 ;check if it's odd or even
BNE SwapRNGifEven
SWAP D0 ;if even, swap the low and high words of D0
SwapRNGifEven:
MOVE.L D0,RNGout_32
rts

View file

@ -0,0 +1,10 @@
macro CloneByte 1
;\1 must be a data register.
;copies the lowest byte to all 4 bytes.
move.b \1,-(SP)
LSL.L #8,\1
move.b (SP)+,\1
pushWord \1
SWAP \1
popWord \1
endm

View file

@ -0,0 +1,38 @@
BEGIN {
# For Windows
out = system2var("dir")
print out
# Non-Windows
out = getline2var("ls -l")
print out
}
# For a Windows environment using system() method
function system2var(command ,tempfile, cmd, out, rec, data, i) {
tempfile = "C:\\TEMP\\TMP.TMP"
cmd = command " > " tempfile
system(cmd)
close(cmd)
while (getline rec < tempfile > 0) {
if ( ++i == 1 )
data = rec
else
data = data "\n" rec
}
return(data)
}
# If command returns an ERRNO function returns null string
function getline2var(command ,fish, scale, ship) {
command = command " 2>/dev/null"
while ( (command | getline fish) > 0 ) {
if ( ++scale == 1 )
ship = fish
else
ship = ship "\n" fish
}
close(command)
return ship
}

View file

@ -0,0 +1,39 @@
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect; use GNAT.Expect;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with GNAT.String_Split; use GNAT.String_Split;
procedure System_Command is
Command : String := "ls -l";
Args : Argument_List_Access;
Status : aliased Integer;
Separators : constant String := LF & CR;
Reply_List : Slice_Set;
begin
Args := Argument_String_To_List (Command);
-- execute the system command and get the output in a single string
declare
Response : String :=
Get_Command_Output
(Command => Args (Args'First).all,
Arguments => Args (Args'First + 1 .. Args'Last),
Input => "",
Status => Status'Access);
begin
Free (Args);
-- split the output in a slice for easier manipulation
if Status = 0 then
Create (S => Reply_List,
From => Response,
Separators => Separators,
Mode => Multiple);
end if;
end;
-- do something with the system output. Just print it out
for I in 1 .. Slice_Count (Reply_List) loop
Put_Line (Slice (Reply_List, I));
end loop;
end System_Command;

View file

@ -0,0 +1 @@
o_("-- ", sshell().plan("expr", "8", "*", "9").link.b_dump('\n'), " --\n");

View file

@ -0,0 +1,6 @@
/* JAMBO language - a flavour of Hopper */
#include <jambo.h>
Main
sys = `cat jm/sys1.jambo`
Set( sys ) Prnl
End

View file

@ -0,0 +1,44 @@
100 HIMEM: 24576
110 LET A = 24576
120 LET P = 768
130 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256
140 DEF FN H(A) = INT (A / 256)
150 DEF FN L(A) = A - FN H(A) * 256
160 POKE P + 00,073: REM EOR
170 POKE P + 01,128: REM #$80
180 POKE P + 02,141: REM STA
190 POKE P + 03, FN L(A)
200 POKE P + 04, FN H(A)
210 POKE P + 05,073: REM EOR
220 POKE P + 06,128: REM #$80
230 POKE P + 07,238: REM INC
240 POKE P + 08, FN L(P + 3)
250 POKE P + 09, FN H(P + 3)
260 POKE P + 10,208: REM BNE
270 POKE P + 11,3
280 POKE P + 12,238: REM INC
290 POKE P + 13, FN L(P + 4)
300 POKE P + 14, FN H(P + 4)
310 POKE P + 15,096: REM RTS
320 POKE 54, FN L(P)
330 POKE 55, FN H(P)
340 CALL 1002
350 PRINT CHR$ (4)"CATALOG"
360 PRINT CHR$ (4)"PR#0"
370 LET C = - 1
380 LET I = 0
390 LET S = 0
400 LET E = FN P(P + 3)
410 DIM S$(54)
420 LET S$(0) = ""
430 POKE 236, PEEK (131)
440 POKE 237, PEEK (132)
450 LET S = FN P(236)
460 FOR I = A TO E STEP 255
470 LET C = C + 1
480 POKE S + C * 3,255
490 IF E - I < 255 THEN POKE S + C * 3,E - I
500 POKE S + C * 3 + 1, FN L(I)
510 POKE S + C * 3 + 2, FN H(I)
520 PRINT S$(C);
530 NEXT

View file

@ -0,0 +1 @@
print split.lines execute "ls"

View file

@ -0,0 +1,4 @@
' Get system command
result$ = EXEC$("fortune")
PRINT CHOP$(result$)
PRINT "First word: " & TOKEN$(result$, 1)

View file

@ -0,0 +1,25 @@
@echo off
setlocal enabledelayedexpansion
:: Without storing the output of the command, it can be viewed by inputting the command
dir
:: Storing the output of 'dir' as "line[]" containing the respective lines of output (starting at line[1])
:: Note: This method removes any empty lines from the output
set tempcount=0
for /f "tokens=*" %%i in ('dir') do (
set /a tempcount+=1
set "line!tempcount!=%%i"
)
:: The array would be viewed like this
for /l %%i in (1,1,%tempcount%) do echo !line%%i!
:: Storing the output of 'dir' in a file, then outputting the contents of the file to the screen
:: NOTE: rewrites any file named "out.temp" in the current directory
dir>out.temp
type out.temp
del out.temp
pause>nul

View file

@ -0,0 +1,3 @@
(system=
.sys$(str$(!arg " > temp"))&get$(temp,STR)
);

View file

@ -0,0 +1 @@
system$ls

View file

@ -0,0 +1,18 @@
#include <fstream>
#include <iostream>
std::string execute(const std::string& command) {
system((command + " > temp.txt").c_str());
std::ifstream ifs("temp.txt");
std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
ifs.close(); // must close the inout stream so the file can be cleaned up
if (std::remove("temp.txt") != 0) {
perror("Error deleting temporary file");
}
return ret;
}
int main() {
std::cout << execute("whoami") << '\n';
}

View file

@ -0,0 +1,34 @@
#include <iostream>
#include <string>
#include <vector>
#include <boost/process.hpp>
// Returns a vector containing names of files in the specified directory
// by capturing the output of the "ls" command, which is specific to
// Unix-like operating systems.
// Obviously there are better ways of listing files in a directory; this
// is just an example showing how to use boost::process.
std::vector<std::string> list_files(const std::string& directory) {
namespace bp = boost::process;
bp::ipstream input;
bp::child process("/bin/ls", directory, bp::std_out > input);
std::vector<std::string> files;
std::string file;
while (getline(input, file))
files.push_back(file);
process.wait();
if (process.exit_code() != 0)
throw std::runtime_error("Process did not complete successfully.");
return files;
}
int main(int argc, char** argv) {
try {
for (auto file : list_files(argc > 1 ? argv[1] : "."))
std::cout << file << '\n';
} catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,20 @@
using System;
namespace GetSystemCommandOutput {
class Program {
static void Main(string[] args) {
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c echo Hello World";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine("Output is {0}", output);
}
}
}

View file

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) return 1;
FILE *fd;
fd = popen(argv[1], "r");
if (!fd) return 1;
char buffer[256];
size_t chread;
/* String to store entire command contents in */
size_t comalloc = 256;
size_t comlen = 0;
char *comout = malloc(comalloc);
/* Use fread so binary data is dealt with correctly */
while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) {
if (comlen + chread >= comalloc) {
comalloc *= 2;
comout = realloc(comout, comalloc);
}
memmove(comout + comlen, buffer, chread);
comlen += chread;
}
/* We can now work with the output as we please. Just print
* out to confirm output is as expected */
fwrite(comout, 1, comlen, stdout);
free(comout);
pclose(fd);
return 0;
}

View file

@ -0,0 +1,2 @@
(use '[clojure.java.shell :only [sh]])
(sh "echo" "Hello")

View file

@ -0,0 +1 @@
(trivial-shell:shell-command "uname -imp")

View file

@ -0,0 +1,4 @@
(defparameter *my-proc*
(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)

View file

@ -0,0 +1 @@
(uiop:run-program '("ls" "-l" "-a") :output :string)

View file

@ -0,0 +1,12 @@
import std.process;
import std.stdio;
void main() {
auto cmd = executeShell("echo hello");
if (cmd.status == 0) {
writeln("Output: ", cmd.output);
} else {
writeln("Failed to execute command, status=", cmd.status);
}
}

View file

@ -0,0 +1,6 @@
// System Command Output. Nigel Galloway: October 6th., 2020
let n=new System.Diagnostics.Process(StartInfo=System.Diagnostics.ProcessStartInfo(RedirectStandardOutput=true,RedirectStandardError=true,UseShellExecute=false,
FileName= @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe",Arguments="--help"))
n.Start()
printfn "%s" ((n.StandardOutput).ReadToEnd())
n.Close()

View file

@ -0,0 +1,2 @@
USING: io.encodings.utf8 io.launcher ;
"echo hello" utf8 [ contents ] with-process-reader .

View file

@ -0,0 +1,9 @@
s" ps " system \ Output only
\ read via pipe into buffer
create buffer 266 allot
s" ps " r/o open-pipe throw
dup buffer swap 256 swap
read-file throw
swap close-pipe throw drop
buffer swap type \ output is the same like above

View file

@ -0,0 +1,16 @@
' FB 1.05.0 Win64
'capture the output of the 'dir' command and print it to a text file
Open "dir_output.txt" For Output As #1
Open Pipe "dir" For Input As #2
Dim li As String
While Not Eof(2)
Line Input #2, li
Print #1, li
Wend
Close #2
Close #1
End

View file

@ -0,0 +1,31 @@
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" ) )
CFArrayRef arguments = fn ArrayWithObjects( @"-c", cmdStr, NULL )
TaskSetArguments( task, arguments )
PipeRef p = fn PipeInit
TaskSetStandardOutput( task, p )
FileHandleRef fh = fn PipeFileHandleForReading( p )
NotificationCenterAddObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification, (FileHandleRef)fh )
fn TaskLaunch( task, NULL )
FileHandleWaitForDataInBackgroundAndNotify( fh )
end fn
fn RunCommand( @"man mdls | col -b" )
HandleEvents

View file

@ -0,0 +1,7 @@
Public Sub Main()
Dim sStore As String
Shell "ls" To sStore
Print sStore
End

View file

@ -0,0 +1,19 @@
[indent=4]
/*
Get system command output, in Genie
valac getSystemCommandOutput.gs
./getSystemCommandOutput
*/
init
try
// Blocking with output capture
standard_output : string
standard_error : string
exit_status : int
Process.spawn_command_line_sync("sh -c 'ls getSys*'",
out standard_output, out standard_error, out exit_status)
print standard_output
except e : SpawnError
stderr.printf("%s\n", e.message)

View file

@ -0,0 +1,15 @@
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
output, err := exec.Command("ls", "-l").CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Print(string(output))
}

View file

@ -0,0 +1,12 @@
#!/usr/bin/env stack
-- stack --resolver lts-8.15 --install-ghc runghc --package process
import System.Process (readProcess)
main :: IO ()
main = do
-- get the output of the process as a list of lines
results <- lines <$> readProcess "hexdump" ["-C", "/etc/passwd"] ""
-- print each line in reverse
mapM_ (putStrLn . reverse) results

View file

@ -0,0 +1,5 @@
100 OPEN #1:"dirinfo.txt" ACCESS OUTPUT
110 SET DEFAULT CHANNEL 1
120 EXT "dir"
130 CLOSE #1
140 SET DEFAULT CHANNEL 0

View file

@ -0,0 +1,23 @@
#
# piped.icn, Get system command output
#
# Dedicated to the public domain
#
procedure main()
# start with an empty list
directory := []
# ls for UNIX, dir for other, assume Windows
command := if &features == "UNIX" then "ls" else "dir"
# open command in pipe mode
p := open(command, "p") | stop("Cannot open pipe for ", command)
# read in results and append to list
while put(directory, read(p))
# display the fifth entry, if there is one
write(\directory[5])
close(p)
end

View file

@ -0,0 +1,5 @@
require 'task'
<shell 'uname -imp'
┌─────────────────────┐
│x86_64 x86_64 x86_64 │
└─────────────────────┘

View file

@ -0,0 +1,19 @@
import java.io.*;
import java.util.*;
public class SystemCommand {
public static void main(String args[]) throws IOException {
String command = "cmd /c dir";
Process p = Runtime.getRuntime().exec(command);
try (Scanner sc = new Scanner(p.getInputStream())) {
System.out.printf("Output of the command: %s %n%n", command);
while (sc.hasNext()) {
System.out.println(sc.nextLine());
}
}
}
}

View file

@ -0,0 +1,2 @@
var commandOutput = exec('ls -gocart', { retAll:true });
puts(commandOutput.data);

View file

@ -0,0 +1 @@
ls = readstring(`ls`)

View file

@ -0,0 +1 @@
ll = readlines(`ls -l`)

View file

@ -0,0 +1,11 @@
// version 1.0.6
import java.util.Scanner
fun main(args: Array<String>) {
val command = "cmd /c chcp"
val p = Runtime.getRuntime().exec(command)
val sc = Scanner(p.inputStream)
println(sc.nextLine())
sc.close()
}

View file

@ -0,0 +1 @@
set rc [system ls -go]

View file

@ -0,0 +1,13 @@
sx = xtra("Shell").new()
put sx.shell_cmd("cd C:\dev\lsw\lib & dir")
-- "
<snip>
31.08.2016 21:25 <DIR> .
31.08.2016 21:25 <DIR> ..
20.08.2016 04:58 <DIR> aes
23.06.2016 18:23 <DIR> audio
21.07.2016 19:19 <DIR> avmedia
23.06.2016 18:22 <DIR> base64
23.06.2016 18:21 <DIR> base9
<snip>"

View file

@ -0,0 +1,2 @@
local output = io.popen("echo Hurrah!")
print(output:read("*all"))

View file

@ -0,0 +1,12 @@
Module CheckIt {
Dos "cd "+quote$(Dir$) +" & cmd /U /C dir *.txt >txt.out";
Document txt$
Repeat {
Wait 100
Try {
load.doc txt$, "txt.out"
}
} Until doc.len(txt$)<>0
Report txt$
}
Checkit

View file

@ -0,0 +1 @@
RunProcess["date"]

View file

@ -0,0 +1,58 @@
/* Get system command output, neko */
var process_run = $loader.loadprim("std@process_run", 2);
var process_stdout_read = $loader.loadprim("std@process_stdout_read", 4);
var process_stderr_read = $loader.loadprim("std@process_stderr_read", 4);
var process_stdin_close = $loader.loadprim("std@process_stdin_close", 1);
var process_exit = $loader.loadprim("std@process_exit", 1);
var sys_exit = $loader.loadprim("std@sys_exit", 1);
/* work buffer */
var bufsize = 1024;
var buffer = $smake(bufsize);
/* default command is ls, otherwise pass command line arguments */
var argc = $asize($loader.args);
var cmd = "ls";
var args;
/* Check command line arguments */
if argc > 0 {
cmd = $loader.args[0];
}
if argc > 1 {
args = $asub($loader.args, 1, argc - 1);
}
/* spawn process, with arguments */
var proc = process_run(cmd, args);
/* Close input channel - command might be waiting for input */
process_stdin_close(proc);
/* capture and print stdout */
var not_done = true;
var len = 0;
do {
try {
len = process_stdout_read(proc, buffer, 0, bufsize);
} catch exc {
not_done = false;
}
if (not_done) $print($ssub(buffer, 0, len));
} while not_done;
/* capture and print any stderr */
not_done = true;
len = 0;
do {
try {
len = process_stderr_read(proc, buffer, 0, bufsize);
} catch exc {
not_done = false;
}
if (not_done) $print($ssub(buffer, 0, len));
} while not_done;
/* Get the exit status */
var ps = process_exit(proc);
sys_exit(ps);

View file

@ -0,0 +1,13 @@
import osproc
# Output string and error code
let (lsalStr, errCode) = execCmdEx("ls -al")
echo "Error code: " & $errCode
echo "Output: " & lsalStr
# Output string only
let lsStr = execProcess("ls")
echo "Output: " & lsStr

View file

@ -0,0 +1,8 @@
class Test {
function : Main(args : String[]) ~ Nil {
output := System.Runtime->CommandOutput("ls -l");
each(i : output) {
output[i]->PrintLine();
};
}
}

View file

@ -0,0 +1,27 @@
/* Execute a system command and retrieve its output into a stem. */
trace normal
/* Make the default values for the stem null strings. */
text. = ''
/* Issue the system command. "address command" is optional.) */
address command 'ls -l | rxqueue'
/* Remember the return code from the command. */
ls_rc = rc
/* Remember the number of lines created by the command. */
text.0 = queued()
/* Fetch each line into a stem variable. */
do t = 1 to text.0
parse pull text.t
end
/* Output each line in reverse order. */
do t = text.0 to 1 by -1
say text.t
end
/* Exit with the system command's return code. */
exit ls_rc

View file

@ -0,0 +1,8 @@
cmd='dir tu*.rex /od'
cmd '| rxqueue'
Say 'Output of "'cmd'"'
Say
Do While queued()>0
parse pull text
Say text
End

View file

@ -0,0 +1,10 @@
dir='dir.dir'
cmd='dir t*.rex /od'
cmd '>'dir
'dir tu*.rex /od >'dir
Say 'Output of "'cmd'"'
Say
Do While lines(dir)>0
Say linein(dir)
End
Call lineout oid

View file

@ -0,0 +1 @@
externstr("time/t")

View file

@ -0,0 +1,5 @@
my @directories = grep { chomp; -d } `ls`;
for (@directories) {
chomp;
...; # Operate on directories
}

View file

@ -0,0 +1,2 @@
my $command = shift or die "No command supplied\n";
my @output_and_errors = qx/$command 2>&1/ or die "Couldn't execute command\n";

View file

@ -0,0 +1,7 @@
use autodie;
my $enc = ':encoding(UTF-8)';
my $child_pid = open(my $pipe, "-|$enc", 'ls');
while (<$pipe>) {
# Print all files whose names are all lowercase
print if m/[^A-Z]+/;
}

View file

@ -0,0 +1,9 @@
(notonline)-->
<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>
<span style="color: #000000;">cmd</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"hostname"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"uname -n"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">system_exec</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%s &gt; %s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">}),</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">host</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_text</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: #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>
<!--

View file

@ -0,0 +1,5 @@
"hostname.txt" var hname
"hostname > " hname chain cmd
hname "r" fopen
dup fgets print fclose
"del " hname chain cmd

View file

@ -0,0 +1,2 @@
: (in '(uname "-om") (line T))
-> "aarch64 Android"

View file

@ -0,0 +1,3 @@
[string[]]$volume = cmd /c vol
$volume

View file

@ -0,0 +1,11 @@
If OpenConsole("ls")
rp=RunProgram("ls", "-l", "",#PB_Program_Open|#PB_Program_Read)
While ProgramRunning(rp)
If AvailableProgramOutput(rp)
r$+ReadProgramString(rp)+#LF$
EndIf
Wend
CloseProgram(rp)
PrintN(r$)
Input()
EndIf

View file

@ -0,0 +1,29 @@
>>> import subprocess
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
<class 'str'>
>>> print(returned_text)
Volume in drive C is Windows
Volume Serial Number is 44X7-73CE
Directory of C:\Python33
04/07/2013 06:40 <DIR> .
04/07/2013 06:40 <DIR> ..
27/05/2013 07:10 <DIR> DLLs
27/05/2013 07:10 <DIR> Doc
27/05/2013 07:10 <DIR> include
27/05/2013 07:10 <DIR> Lib
27/05/2013 07:10 <DIR> libs
16/05/2013 00:15 33,326 LICENSE.txt
15/05/2013 22:49 214,554 NEWS.txt
16/05/2013 00:03 26,624 python.exe
16/05/2013 00:03 27,136 pythonw.exe
15/05/2013 22:49 6,701 README.txt
27/05/2013 07:10 <DIR> tcl
27/05/2013 07:10 <DIR> Tools
16/05/2013 00:02 43,008 w9xpopen.exe
6 File(s) 351,349 bytes
9 Dir(s) 46,326,947,840 bytes free
>>> # Ref: https://docs.python.org/3/library/subprocess.html

View file

@ -0,0 +1 @@
system("wc -l /etc/passwd /etc/group", intern = TRUE)

View file

@ -0,0 +1,11 @@
/*REXX program executes a system command and displays the results (from an array). */
parse arg xxxCmd /*obtain the (system) command from CL.*/
trace off /*suppress REXX error msgs for fails. */
@.= 0 /*assign default in case ADDRESS fails.*/
address system xxxCmd with output stem @. /*issue/execute the command and parms. */
if rc\==0 then say copies('', 40) ' return code ' rc " from: " xxxCmd
/* [↑] display if an error occurred.*/
do #=1 for @.0 /*display the output from the command. */
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. */

View file

@ -0,0 +1,28 @@
#lang racket/base
(require racket/system
(only-in racket/port with-output-to-string)
tests/eli-tester)
(test
;; system runs command and outputs to current output port (which is stdout unless we catch it)
(system "ls /etc/motd") => #t
;; it throws an error on non-zero exit code (so I need to catch it in this error handler)
(system "false") => #f ; nothing printed to stdout/stderr
(system "ls /etc/mosh") => #f ; error report printed to stderr
;; output can be captured by redirecting stdout/stderr (which are known as current-output-port and
;; current-error-port in racket parlance).
;; the command printed a \n, so there is a newline captured by the system command
(with-output-to-string (λ () (system "ls /etc/motd"))) => "/etc/motd\n"
;; no \n is captured when none is captured
(with-output-to-string (λ () (system "echo -n foo"))) => "foo"
;; error is still not captured (it's still printed to stderr)
(with-output-to-string (λ () (system "echo -n foo; echo bar 1>&2"))) => "foo"
;; we can capture both with:
(let* ((out-str-port (open-output-string))
(err-str-port (open-output-string))
(system-rv
(parameterize ((current-output-port out-str-port) (current-error-port err-str-port))
(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"))

View file

@ -0,0 +1 @@
say run($command, $arg1, $arg2, :out).out.slurp;

View file

@ -0,0 +1,3 @@
my $p1 = run 'echo', 'Hello, world', :out;
my $p2 = run 'cat', '-n', :in($p1.out), :out;
say $p2.out.slurp-rest;

View file

@ -0,0 +1 @@
say qx[dir]

View file

@ -0,0 +1 @@
system("dir C:\Ring\doc")

View file

@ -0,0 +1,2 @@
str = `ls`
arr = `ls`.lines

View file

@ -0,0 +1,2 @@
a$ = shell$("dir") ' Returns the directory info into a$
print a$ ' prints the directory

View file

@ -0,0 +1,11 @@
use std::process::Command;
use std::io::{Write, self};
fn main() {
let output = Command::new("/bin/cat")
.arg("/etc/fstab")
.output()
.expect("failed to execute process");
io::stdout().write(&output.stdout);
}

View file

@ -0,0 +1,6 @@
import scala.io.Source
val command = "cmd /c echo Time at %DATE% %TIME%"
val p = Runtime.getRuntime.exec(command)
val sc = Source.fromInputStream(p.getInputStream)
println(sc.mkString)

View file

@ -0,0 +1,2 @@
var output = `ls` # `output` is a string
var lines = `ls`.lines # `lines` is an array

View file

@ -0,0 +1,4 @@
var pipe = %p(ls) # same as: Pipe('ls')
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 }

View file

@ -0,0 +1,26 @@
val useOS = fn input =>
let
val text = String.translate (fn #"\"" => "\\\""|n=>str n ) input ;
val shellCommand = " echo " ^ text ^ "| gzip -c " ;
val fname = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
val me = ( Posix.FileSys.mkfifo
(fname,
Posix.FileSys.S.flags [ Posix.FileSys.S.irusr,Posix.FileSys.S.iwusr ]
) ;
Posix.Process.fork ()
) ;
in
if (Option.isSome me) then
let
val fin =BinIO.openIn fname
in
( Posix.Process.sleep (Time.fromReal 0.1) ;
BinIO.inputAll fin before
(BinIO.closeIn fin ; OS.FileSys.remove fname )
)
end
else
( OS.Process.system ( shellCommand ^ " > " ^ fname ^ " 2>&1 " ) ;
Word8Vector.fromList [] before OS.Process.exit OS.Process.success
)
end;

View file

@ -0,0 +1,15 @@
program shellout, rclass
tempfile f
tempname m
shell `0' > `f'
file open `m' using "`f'", read binary
file seek `m' eof
file seek `m' query
local n=r(loc)
if `n'>0 {
file seek `m' tof
file read `m' %`n's s
file close `m'
return local out "`s'"
}
end

View file

@ -0,0 +1,8 @@
. shellout dir /b *.dta
. display r(out)
auto.dta
titanium.dta
. shellout python -V
. display r(out)
Python 3.6.2

View file

@ -0,0 +1,16 @@
import Foundation
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = ["pwd"]
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String.init(data: data, encoding: String.Encoding.utf8)
print(output!)

View file

@ -0,0 +1,2 @@
set data [exec ls -l]
puts "read [string length $data] bytes and [llength [split $data \n]] lines"

View file

@ -0,0 +1 @@
set data [exec {*}[auto_execok DIR]]

View file

@ -0,0 +1,5 @@
# This syntax is pretty ugly, alas
set pipe [open |[list ls -l] "r"]
fconfigure $pipe -encoding iso8859-1 -translation lf
set data [read $pipe]
close $pipe

View file

@ -0,0 +1,40 @@
> decl iodevice iod
> decl string<> arg
> append "ifconfig" arg
> set iod (ursa.util.process.start arg)
> decl string<> output
> set output (iod.readlines)
> for (decl int i) (< i (size output)) (inc i)
.. out output<i> endl console
..end for
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=1<PERFORMNUD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=27<RXCSUM,TXCSUM,VLAN_MTU,TSO4>
ether d4:9a:20:b8:8d:2c
nd6 options=1<PERFORMNUD>
media: autoselect
status: inactive
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 00:26:08:e0:67:cc
inet6 fe80::226:8ff:fee0:67cc%en1 prefixlen 64 scopeid 0x5
inet 172.20.30.66 netmask 0xffffff00 broadcast 172.20.30.255
nd6 options=1<PERFORMNUD>
media: autoselect
status: active
fw0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 4078
lladdr d4:9a:20:ff:fe:b8:8d:2c
nd6 options=1<PERFORMNUD>
media: autoselect <full-duplex>
status: inactive
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 02:26:08:e0:67:cc
media: autoselect
status: inactive
>

View file

@ -0,0 +1,20 @@
For Each line In ExecCmd("ipconfig /all")
Wscript.Echo line
Next
'Execute the given command and return the output in a text array.
Function ExecCmd(cmd)
'Execute the command
Dim wso : Set wso = CreateObject("Wscript.Shell")
Dim exec : Set exec = wso.Exec(cmd)
Dim res : res = ""
'Read all result text from standard output
Do
res = res & VbLf & exec.StdOut.ReadLine
Loop Until exec.StdOut.AtEndOfStream
'Return as a text array
ExecCmd = Split(Mid(res,2),vbLf)
End Function

View file

@ -0,0 +1,20 @@
Module Module1
Sub Main()
Dim proccess As New Process
Dim startInfo As New ProcessStartInfo
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.FileName = "cmd.exe"
startInfo.Arguments = "/c echo Hello World"
startInfo.RedirectStandardOutput = True
startInfo.UseShellExecute = False
proccess.StartInfo = startInfo
proccess.Start()
Dim output = proccess.StandardOutput.ReadToEnd
Console.WriteLine("Output is {0}", output)
End Sub
End Module

View file

@ -0,0 +1,6 @@
/* get_system_command_output.wren */
class Command {
foreign static output(name, param) // the code for this is provided by Go
}
System.print(Command.output("ls", "-ls"))

View file

@ -0,0 +1,39 @@
/* get_system_command_output.go */
package main
import (
wren "github.com/crazyinfin8/WrenGo"
"log"
"os"
"os/exec"
)
type any = interface{}
func getCommandOutput(vm *wren.VM, parameters []any) (any, error) {
name := parameters[1].(string)
param := parameters[2].(string)
var cmd *exec.Cmd
if param != "" {
cmd = exec.Command(name, param)
} else {
cmd = exec.Command(name)
}
cmd.Stderr = os.Stderr
bytes, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
return string(bytes), nil
}
func main() {
vm := wren.NewVM()
fileName := "get_system_command_output.wren"
methodMap := wren.MethodMap{"static output(_,_)": getCommandOutput}
classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)}
module := wren.NewModule(classMap)
vm.SetModule(fileName, module)
vm.InterpretFile(fileName)
vm.Free()
}

View file

@ -0,0 +1,12 @@
// Rosetta Code problem: https://www.rosettacode.org/wiki/Get_system_command_output
// by Jjuanhdez, 06/2022
if peek$("os") = "unix" then
c$ = "ls *"
else //"windows"
c$ = "dir *.*"
fi
open("dir_output.txt") for writing as #1
print #1 system$(c$)
close #1

View file

@ -0,0 +1,4 @@
zkl: System.cmd("date >foo.txt")
0 // date return code
zkl: File("foo.txt").read().text
Wed Aug 20 00:28:55 PDT 2014