#🔒 Checking `subprocess.run` code

16 messages · Page 1 of 1 (latest)

dapper gale
#

How does this code look in terms of errors and performance -

  1. Until yesterday, I had no idea what subprocess does. I wrote this code looking at various blogs. Therefore, could someone please have a look and see if I made any glaring error.
  2. Am I missing any convenient feature that experienced programs that add with the run command?
import subprocess
with open("stdout.txt", "w") as stdout, open("stderr.txt", "w") as stderr:
    result = subprocess.run(["bash", "test.sh", "2"], stdout=stdout, stderr=stderr,text=True, check=True)

This is my bash script -

echo "Hello World $1"
printf

printf was added to ensure that an error will be created

Please let me know if you have any questions. Thank you!

vivid lodgeBOT
#

@dapper gale

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

bright jungle
#

You can add capture_output=True, encoding="utf8" if you only have a small amount of output

#

text=True does nothing for files passed as stderr/stdout the stderr.fileno()/stdout.fileno() is passed directly to the subprocess to write bytes into

dapper gale
dapper gale
bright jungle
#

And it might be clearer to open the files in binary mode

dapper gale
bright jungle
#

You'll see that you're still able to view the files

#

All text mode does is add a wrapper object that decodes/encodes text to/from bytes

#

files can ultimately only contain bytes

dapper gale
#

Ah. I see.

#

Thank you!

vivid lodgeBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.