4/24/2021 0 Comments Python Subprocess Module
Subprocess is a built-in Python module that can be used to create new processes and interact with their input and output data streams.In simpler terms, you can use it to run shell commands and run executable binaries usually scattered in various bin folders across a Linux file system.
You can also supply a full path to an executable binary and use any command-line switches associated with the binary. Python Subprocess Module How To Use TheThis article will explain how to use the subprocess module and its run method in Python apps. Python Subprocess Module Code Samples InAll code samples in the article are tested with Python 3.8.2 on Ubuntu 20.04. When the method is called, it executes the command and waits for the process to finish, returning a CompletedProcess object in the end. The CompletedProcess object returns stdout, stderr, original arguments used while calling the method, and a return code. Stdout refers to the data stream produced by the command, while stderr refers to any errors raised during execution of the program. Any non-zero return code (exit code) would mean error with the command executed in the subprocess.run method. Any element in the list that follows the first element are considered command-line options or switches. You can use single dash and double dashes, as well, to define the options. For example, to list files and folders in a directory, the code would be subprocess.run(ls, -l. In most of these cases, you can consider any space-separated argument in a shell command as an individual element in the list supplied to the subprocess.run method. You can also supply textTrue as an extra argument to the subprocess.run call to get the output in string format. To get exit status code, you can use the output.returncode method. To do this, you must pass shellTrue as an additional argument. This is however, discouraged by python developers as using shellTrue can lead to security issues. This helps in limiting all code to python itself without the need to have additional shell script code in separate files. It can be, however, quite tricky to correctly tokenize shell commands in a python list. You can use the shlex.split() method to tokenize simple shell commands, but in long, complex commands especially those with pipe symbols shlex fails to correctly split the command. You can use the shellTrue argument to avoid this, but there are certain security concerns associated with this action.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |