As an example, this pattern could be useful if we wanted to raise an exception in the event that we run git ls-files in a directory that wasn’t actually a git repository. Programs that exit with a zero code are considered successful, but programs that exit with a non-zero code are considered to have encountered an error. Sometimes it’s useful to raise an exception if a program we run exits with a bad exit code. This is because by default Python writes the Traceback of the unhandled exception to stderr. When we inspect the final result, we see nothing in stdout and a Traceback of our ValueError in stderr. This code runs a Python subprocess that immediately raises a ValueError. Stderr: Traceback (most recent call last): If we run this code, we receive output like the following: run (, capture_output = True, text = True ) print ( "stdout:", result. Let’s try an example that produces a non-empty value for stderr: import subprocess In the output section, stdout is ocean (plus the trailing newline that print adds implicitly), and we have no stderr. By default, result.stdout and result.stderr are bound as bytes, but the text=True keyword argument instructs Python to instead decode the bytes into strings. capture_output=True ensures that result.stdout and result.stderr are filled in with the corresponding output from the external program. The subprocess.CompletedProcess object includes details about the external program’s exit code and its output. n returns a subprocess.CompletedProcess object that is bound to result. Importantly, however, we pass the capture_output=True and text=True keyword arguments to n. This example is largely the same as the one introduced in the first section: we are still running a subprocess to print ocean. ![]() Note that subprocess automatically quotes the components of the command before trying to run them on the underlying operating system so that, for example, you can pass a filename that has spaces in it. ![]() For example, translates roughly to /usr/local/bin/python -c "print('ocean')". You can think of each entry in the list that we pass to n as being separated by a space. In our case, we pass a program that prints the string ocean.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |