进行系统调用,将stdout输出作为字符串返回
-
04-07-2019 - |
题
Perl和PHP使用反引号执行此操作。例如,
$output = `ls`;
返回目录列表。类似的函数system("foo")
返回给定命令foo的操作系统返回码。我正在谈论一个将foo打印返回到stdout的变体。
其他语言如何做到这一点?这个函数有一个规范名称吗? (我要用<!> quot; backtick <!>引用;;虽然也许我可以硬币<!>“; syslurp <!>”。)
解决方案 20
的Perl:
$output = `foo`;
ADDED:这真的是一个多方面的关系。以上也是有效的PHP,例如,Ruby也使用相同的反引号表示法。
其他提示
的Python
from subprocess import check_output as qx
output = qx(['ls', '-lt'])
Python <!> lt; 2.7 或<! > lt; 3.1
从 subprocess.py 提取subprocess.check_output()
a>或改编类似的东西:
import subprocess
def cmd_output(args, **kwds):
kwds.setdefault("stdout", subprocess.PIPE)
kwds.setdefault("stderr", subprocess.STDOUT)
p = subprocess.Popen(args, **kwds)
return p.communicate()[0]
print cmd_output("ls -lt".split())
自2.4以来,子流程模块一直在stdlib中。
的Python:
import os
output = os.popen("foo").read()
[应 Alexman 和 dreeves - 见评论 - ,你会发现 DZones Java Snippet页面 完整版本独立于Os,用于制作”ls“。这是他们的 代码挑战 的即可。结果 下面的内容只是核心:Runtime.exec,加上2个线程来监听stdout和stderr。 ]
Java <!>“简单!<!>”:
E:\classes\com\javaworld\jpitfalls\article2>java GoodWindowsExec "dir *.java"
Executing cmd.exe /C dir *.java
...
或者在java代码中
String output = GoodWindowsExec.execute("dir");
但要做到这一点,你需要编码......
......这很尴尬。
import java.util.*;
import java.io.*;
class StreamGobbler extends Thread
{
InputStream is;
String type;
StringBuffer output = new StringBuffer();
StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
output.append(line+"\r\n")
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public String getOutput()
{
return this.output.toString();
}
}
public class GoodWindowsExec
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java GoodWindowsExec <cmd>");
System.exit(1);
}
}
public static String execute(String aCommand)
{
String output = "";
try
{
String osName = System.getProperty("os.name" );
String[] cmd = new String[3];
if( osName.equals( "Windows 95" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = aCommand;
}
else if( osName.startsWith( "Windows" ) )
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = aCommand;
}
Runtime rt = Runtime.getRuntime();
System.out.println("Executing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
output = outputGobbler.getOutput();
System.out.println("Final output: " + output);
} catch (Throwable t)
{
t.printStackTrace();
}
return output;
}
}
在Perl中实现它的另一种方法(TIMTOWTDI)
$output = <<`END`;
ls
END
在Perl程序中嵌入相对较大的shell脚本时,这非常有用
Ruby:反引号或'%x'内置语法。
puts `ls`;
puts %x{ls};
perl中的另一种方法
$output = qx/ls/;
这样做的好处是你可以选择你的分隔符,这样就可以在命令中使用`(虽然恕我直言,你应该重新考虑你的设计,如果你真的需要这样做)。另一个重要的优点是,如果使用单引号作为分隔符,则不会插入变量(非常有用)
Haskell中:
import Control.Exception
import System.IO
import System.Process
main = bracket (runInteractiveCommand "ls") close $ \(_, hOut, _, _) -> do
output <- hGetContents hOut
putStr output
where close (hIn, hOut, hErr, pid) =
mapM_ hClose [hIn, hOut, hErr] >> waitForProcess pid
安装了 MissingH :
import System.Cmd.Utils
main = do
(pid, output) <- pipeFrom "ls" []
putStr output
forceSuccess pid
这是<!>“胶水<!>”中的简单操作。像Perl和Ruby这样的语言,但Haskell不是。
在shell中
OUTPUT=`ls`
或者
OUTPUT=$(ls)
第二种方法更好,因为它允许嵌套,但与第一种方法不同,所有shell都不支持。
二郎:
os:cmd("ls")
好吧,因为这是依赖于系统的,所以有许多语言没有内置的包装器来处理所需的各种系统调用。
例如,Common Lisp本身并不是为在任何特定系统上运行而设计的。然而,SBCL(Steel Banks Common Lisp实现)确实为类Unix系统提供了扩展,大多数其他CL实现也是如此。这更像是<!>“强大的<!>”;当然,不仅仅是获取输出(你可以控制运行过程,可以指定所有类型的流方向等,参考SBCL手册,第6.3章),但是为这个特定的内容编写一个小宏很容易目的:
(defmacro with-input-from-command ((stream-name command args) &body body) "Binds the output stream of command to stream-name, then executes the body in an implicit progn." `(with-open-stream (,stream-name (sb-ext:process-output (sb-ext:run-program ,command ,args :search t :output :stream))) ,@body))
现在,您可以像这样使用它:
(with-input-from-command (ls "ls" '("-l")) ;;do fancy stuff with the ls stream )
也许你想把它全部塞进一个字符串中。宏是微不足道的(虽然可能更简洁的代码):
(defmacro syslurp (command args) "Returns the output from command as a string. command is to be supplied as string, args as a list of strings." (let ((istream (gensym)) (ostream (gensym)) (line (gensym))) `(with-input-from-command (,istream ,command ,args) (with-output-to-string (,ostream) (loop (let ((,line (read-line ,istream nil))) (when (null ,line) (return)) (write-line ,line ,ostream)))))))
现在你可以通过这个电话获得一个字符串:
(syslurp "ls" '("-l"))
数学:
output = Import["!foo", "Text"];
多年前我为插件与本机应用程序连接的“rel =”nofollow noreferrer“> jEdit 。这就是我用来从正在运行的可执行文件中获取流的内容。只剩下要做的事是while((String s = stdout.readLine())!=null){...}
:
/* File: IOControl.java
*
* created: 10 July 2003
* author: dsm
*/
package org.jpop.io;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
/**
* Controls the I/O for a process. When using the std[in|out|err] streams, they must all be put on
* different threads to avoid blocking!
*
* @author dsm
* @version 1.5
*/
public class IOControl extends Object {
private Process process;
private BufferedReader stdout;
private BufferedReader stderr;
private PrintStream stdin;
/**
* Constructor for the IOControl object
*
* @param process The process to control I/O for
*/
public IOControl(Process process) {
this.process = process;
this.stdin = new PrintStream(process.getOutputStream());
this.stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
this.stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
}
/**
* Gets the stdin attribute of the IOControl object
*
* @return The stdin value
*/
public PrintStream getStdin() {
return this.stdin;
}
/**
* Gets the stdout attribute of the IOControl object
*
* @return The stdout value
*/
public BufferedReader getStdout() {
return this.stdout;
}
/**
* Gets the stderr attribute of the IOControl object
*
* @return The stderr value
*/
public BufferedReader getStderr() {
return this.stderr;
}
/**
* Gets the process attribute of the IOControl object. To monitor the process (as opposed to
* just letting it run by itself) its necessary to create a thread like this: <pre>
*. IOControl ioc;
*.
*. new Thread(){
*. public void run(){
*. while(true){ // only necessary if you want the process to respawn
*. try{
*. ioc = new IOControl(Runtime.getRuntime().exec("procname"));
*. // add some code to handle the IO streams
*. ioc.getProcess().waitFor();
*. }catch(InterruptedException ie){
*. // deal with exception
*. }catch(IOException ioe){
*. // deal with exception
*. }
*.
*. // a break condition can be included here to terminate the loop
*. } // only necessary if you want the process to respawn
*. }
*. }.start();
* </pre>
*
* @return The process value
*/
public Process getProcess() {
return this.process;
}
}
不要忘记Tcl:
set result [exec ls]
C#3.0,比这一个:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
var info = new ProcessStartInfo("cmd", "/c dir") { UseShellExecute = false, RedirectStandardOutput = true };
Console.WriteLine(Process.Start(info).StandardOutput.ReadToEnd());
}
}
警告:生产代码应该正确处理Process对象......
另一种方式(或2!)在Perl ....
open my $pipe, 'ps |';
my @output = < $pipe >;
say @output;
open 也可以这样编写......
open my $pipe, '-|', 'ps'
在PHP中
$output = `ls`;
或
$output = shell_exec('ls');
C(带glibc
扩展名):
#define _GNU_SOURCE
#include <stdio.h>
int main() {
char *s = NULL;
FILE *p = popen("ls", "r");
getdelim(&s, NULL, '\0', p);
pclose(p);
printf("%s", s);
return 0;
}
好的,不是很简洁或干净。这就是C ......的生活。
符合Posix标准的系统中的C:
#include <stdio.h>
FILE* stream = popen("/path/to/program", "rw");
fprintf(stream, "foo\n"); /* Use like you would a file stream. */
fclose(stream);
为什么这里仍然没有c#人:)
这是如何在C#中完成的。内置方式。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "/c dir";
p.Start();
string res = p.StandardOutput.ReadToEnd();
Console.WriteLine(res);
}
}
}
这是另一种Lisp方式:
(defun execute (program parameters &optional (buffer-size 1000))
(let ((proc (sb-ext:run-program program parameters :search t :output :stream))
(output (make-array buffer-size :adjustable t :fill-pointer t
:element-type 'character)))
(with-open-stream (stream (sb-ext:process-output proc))
(setf (fill-pointer output) (read-sequence output stream)))
output))
然后,获取你的字符串:
(execute "cat" '("/etc/hosts"))
如果你想运行一个命令来创建STDOUT的大量信息,你可以像这样运行它:
(execute "big-writer" '("some" "parameters") 1000000)
最后一个参数为big-writer的输出预分配了大量空间。我猜这个函数可能比一次读取一行输出流更快。
Lua :
foo = io.popen("ls"):read("*a")
J :
output=:2!:0'ls'
Perl,另一种方式:
use IPC::Run3
my ($stdout, $stderr);
run3 ['ls'], undef, \$stdout, \$stderr
or die "ls failed";
很有用,因为您可以提供命令输入,并分别返回stderr和stdout。没有像IPC::Run
那样整洁/可怕/缓慢/令人不安,这可以设置管道到子程序。
图标/ UNICON:
stream := open("ls", "p")
while line := read(stream) do {
# stuff
}
文档称之为管道。其中一个好处是它使输出看起来像你只是在阅读文件。这也意味着如果必须,你可以写入应用程序的标准输入。
Clozure Common Lisp:
(with-output-to-string (stream)
(run-program "ls" '("-l") :output stream))
LispWorks
(with-output-to-string (*standard-output*)
(sys:call-system-showing-output "ls -l" :prefix "" :show-cmd nil))
当然,它不是较小的(来自所有可用的语言)但它不应该那么冗长。
此版本很脏。应该处理例外情况,可以改进阅读。这只是为了展示java版本的启动方式。
Process p = Runtime.getRuntime().exec( "cmd /c " + command );
InputStream i = p.getInputStream();
StringBuilder sb = new StringBuilder();
for( int c = 0 ; ( c = i.read() ) > -1 ; ) {
sb.append( ( char ) c );
}
完整的程序如下。
import java.io.*;
public class Test {
public static void main ( String [] args ) throws IOException {
String result = execute( args[0] );
System.out.println( result );
}
private static String execute( String command ) throws IOException {
Process p = Runtime.getRuntime().exec( "cmd /c " + command );
InputStream i = p.getInputStream();
StringBuilder sb = new StringBuilder();
for( int c = 0 ; ( c = i.read() ) > -1 ; ) {
sb.append( ( char ) c );
}
i.close();
return sb.toString();
}
}
示例输出(使用type命令)
C:\oreyes\samples\java\readinput>java Test "type hello.txt"
This is a sample file
with some
lines
示例输出(dir)
C:\oreyes\samples\java\readinput>java Test "dir"
El volumen de la unidad C no tiene etiqueta.
El número de serie del volumen es:
Directorio de C:\oreyes\samples\java\readinput
12/16/2008 05:51 PM <DIR> .
12/16/2008 05:51 PM <DIR> ..
12/16/2008 05:50 PM 42 hello.txt
12/16/2008 05:38 PM 1,209 Test.class
12/16/2008 05:47 PM 682 Test.java
3 archivos 1,933 bytes
2 dirs 840 bytes libres
尝试任何
java Test netstat
java Test tasklist
java Test "taskkill /pid 416"
修改强>
我必须承认,我不是100%确定这是<!>“最好的<!>”;这样做的方式。随意发布参考文献和/或代码,以显示如何改进或错误。