How to call an external program in python and retrieve the output and return code?

后端 未结 5 890
深忆病人
深忆病人 2020-11-27 15:42

How can I call an external program with a python script and retrieve the output and return code?

5条回答
  •  北海茫月
    2020-11-27 16:26

    I've developed a little library (py-execute) that allows you to execute external programs, retrieve the output and the retcode and, at the same time get output in console in real time:

    >>> from py_execute.process_executor import execute
    >>> ret = execute('echo "Hello"')
    Hello
    >>> ret
    (0, 'Hello\n')
    

    You can avoid printing to console passing a mock user_io:

    >>> from mock import Mock
    >>> execute('echo "Hello"', ui=Mock())
    (0, 'Hello\n')
    

    I wrote it because with plain Popen (In Python 2.7) I was having trouble executing commands with a long output

提交回复
热议问题