1

How to split stdout of subprocess.run in python()

Code:

def run(self):
    command = ls
    result = subprocess.run(
        [command],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True
    )
    self.returncode = result.returncode
    self.stderr = result.stderr
    self.stdout = result.stdout
    os.chdir(CDW)
    print(self.stderr)

Result:

b'file1.txt\nfile2.txt\nfile3\n'

Expected Result

file1
file2
file3
accdias
  • 5,160
  • 3
  • 19
  • 31
  • It's unlikely you want `shell=True` if you are passing a list as the first argument to `subproces.run`. (I'm assuming the first line should be `command = "ls"`.) – chepner Mar 08 '22 at 18:22

2 Answers2

0

Decode the string first; you are getting a string representation of a bytes value.

print(self.stderr.decode())

You can also have subprocess.run decode the string for you by passing text=True as an argument.

result = subprocess.run(
                [command],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Add the following line

stdout_as_str = result.stdout.decode("utf-8")

Final code

 def run(self):
        os.chdir(self.directory)
        if os.path.isdir("mlc"):
            pass
        else:
            self.download()
        os.chdir("mlc/Linux/")
        subprocess.call(["chmod", "+x", "mlc_internal"])
        result = subprocess.run(
            [self.mlc_command],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True,
        )
        stdout_as_str = result.stdout.decode("utf-8")
        print(stdout_as_str)