Search code examples
pythonmacossudo

How to convert output from Python after sudo command from <type> int to <type> str?


I have the following code to receive list of process with sudo:

sudoPass = 'mypass'
command = "launchctl list | grep -v com.apple"
x = os.system('echo %s|sudo -S %s' % (sudoPass, command))

But, I receive answer in int. I need in str. Is it possible to convert it to str without loosing data?


Solution

  • os.system returns (in most cases, see https://docs.python.org/3/library/os.html#os.system) the exit value of the process. Meaning most of the time 0 is everything went fine.

    What you look for is the subprocess module (https://docs.python.org/3/library/subprocess.html) that allow you to capture output like so :

    import subprocess
    sudoPass = 'mypass\n' #Note the new line
    command = "launchctl list | grep -v com.apple"
    x = subprocess.Popen('echo %s|sudo -S %s' % (sudoPass, command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout, stderr = x.communicate()
    print(stdout)