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

前端 未结 27 1137
误落风尘
误落风尘 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条回答
  •  萌比男神i
    2020-11-27 05:36

    Python

    from subprocess import check_output as qx
    
    output = qx(['ls', '-lt'])
    

    Python <2.7 or <3.1

    Extract subprocess.check_output() from subprocess.py or adapt something similar to:

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

    The subprocess module has been in the stdlib since 2.4.

提交回复
热议问题