Gaurav Pathak
Gaurav Pathak

Reputation: 45

python subprocess, redirecting exit code to a file

Using subprocess run()/popen(), we are able redirect stdout and stderr to an external file. Is there any way to also redirect exit code as well?

Upvotes: 1

Views: 152

Answers (1)

TheEagle
TheEagle

Reputation: 5982

Just read the returncode attribute of the returned object of subprocess.run, and write that to a file.

import subprocess

r = subprocess.run(["ls"])
with open("returncode.txt", "w") as f:
    f.write(str(r.returncode))

Upvotes: 2

Related Questions