Making a system call that returns the stdout output as a string

前端 未结 27 859
误落风尘
误落风尘 2020-11-27 05:13

Perl and PHP do this with backticks. For example,

$output = `ls`;

Returns a directory listing. A similar function, system(\"foo\")

相关标签:
27条回答
  • 2020-11-27 05:40

    Yet another way to do it in Perl (TIMTOWTDI)

    $output = <<`END`;
    ls
    END
    

    This is specially useful when embedding a relatively large shell script in a Perl program

    0 讨论(0)
  • 2020-11-27 05:43

    Python:

    import os
    output = os.popen("foo").read()
    
    0 讨论(0)
  • 2020-11-27 05:43

    In shell

    OUTPUT=`ls`
    

    or alternatively

    OUTPUT=$(ls)
    

    This second method is better because it allows nesting, but isn't supported by all shells, unlike the first method.

    0 讨论(0)
  • 2020-11-27 05:43

    Yet another way (or 2!) in Perl....

    open my $pipe, 'ps |';
    my @output = < $pipe >;
    say @output;
    

    open can also be written like so...

    open my $pipe, '-|', 'ps'
    
    0 讨论(0)
  • 2020-11-27 05:43

    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))
    
    0 讨论(0)
  • 2020-11-27 05:46

    Mathematica:

    output = Import["!foo", "Text"];
    
    0 讨论(0)
提交回复
热议问题