Output from subprocess.Popen

后端 未结 3 416
耶瑟儿~
耶瑟儿~ 2021-01-18 23:46

I\'ve been writing some python code and in my code I was using \"command\"

The code was working as I intended but then I noticed in the Python docs that command has

3条回答
  •  再見小時候
    2021-01-19 00:51

    See the subprocess module documentation for more information.

    Here is how to get stdout and stderr from a program using the subprocess module:

    from subprocess import Popen, PIPE, STDOUT
    
    cmd = 'echo Hello World'
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    output = p.stdout.read()
    print output
    

    results:

    b'Hello\r\n'
    

    you can run commands with PowerShell and see results:

    from subprocess import Popen, PIPE, STDOUT
    cmd = 'powershell.exe ls'
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    output = p.stdout.read()
    

    useful link

提交回复
热议问题