An Introduction to Subprocess in Python with Examples (2023)

A Python subprocess

Starting new processes uses the Python function's subprocess to run additional programs and applications. It makes it possible to run new applications directly from a programming language that you develop. To launch remote applications from just a source code repository or programming in C as well as C++, you can choose to use a subprocess in Python. With Python, you can use subprocesses to escape code or corrupted input, output, or streams.

Introduction to the Python subprocess

If you've always used Python alongside controller programs and other services of that nature and want to improve regular command-line coding, the Pythons subprocess can be useful. Python's subprocess function can support a variety of tasks, including launching graphical user interfaces and running command-line programs.

Also remember that a parent process is the place where all tasks in the sub-process complete. Python has been used to refer to a variety of tasks and underlying operations as processes. The upper process is what it's called.

  • Operations that can only complete before a process can complete are normally shown.
  • And then someone has to do these activities for this higher level procedure. The subprocess is born there from the parent process.
  • A process can spawn a subprocess to handle urgent work while the main process is still active.
  • This facilitates and improves data and storage management. Python lets you break up larger jobs into smaller subprocesses that can handle simpler tasks in one process, allowing you to run many processes at the same time.
  • And the name of the whole process is multiprocessing.

How do we start a Python process?

In Python, you must use the Popen function call to start a new process, i.e. a new subprocess. When calling the method, two arguments can be passed. The application you want to launch is the start parameter and the file argument is next. The Unix command cat and demo.py are used as the two arguments in the following code. Concatenate or cat is a universally popular and effective command in Unix and Linux software. Similar to cat demo.py, except if we didn't build the software, you can launch it.

Example:

# Programa para iniciar um novo processo# import popen and pipe modulefrom subprocess import Popen, PIPE# declare the processp = Popen(['cat', 'demo.py'], stdout=PIPE, stderr=PIPE)stdout, stderr = p .communicate()# mostra o stdoutprint(stdout)

The main call that gets all process inputs and outputs in the above program is process. to communicate(). Process output is handled by stdout and all errors are handled by stderr, which is only generated when such an error is thrown.

The subprocess call()

What is that?

Python's subprocess contains a call() function that is used to launch an application. The line of code for this subprocess call() method is as follows:

Syntax

# Execute the command specified by args.# Return the attribute with the return code upon completion of the command.subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Conditions for Subprocess Call()

The following arguments are accepted by the subprocess Python call() function, they are

  1. argument
  2. stdin
  3. stdout
  4. stderr
  5. manga

Arguments:

This would be the Python statement that should be used to start a subprocess. We could provide multiple statements just by separating them with a single semicolon (;).

stdin:

For something like the general input stream, this means the value provided as (os.pipe()) .

Standard output:

It serves as a representation of the result of the output stream.

stderr:

Any errors that came through the shell's standard error stream are covered here.

manga:

If left true, the shell boolean argument will cause the application to run in a new shell.

return the value

The return value of a subprocess's Python Call() method can be specified as follows. The program execution code is returned by the call() method of the subprocess in Python. The function returns successfully executed encoding when there is no program output. Additionally, a CalledProcessError exception might be thrown.

Then call a subprocess again for the Unix constructed command "ls -l" using a simple example. The contents of a directory are listed in full with the ls command and expanded with the -l command.

Code

# import subprocess moduleimport subprocesssubprocess.call(["ls", "-l"])

The result only shows the total number of files and the time and date at the current time.

Save process output (stdout)

What does Python's Save Output Values ​​(stdout) subprocess function do? Using the check output function, a save process output via stdout allows you to immediately preserve the result of a code in a string. The syntax of this strategy is as follows:

Syntax

# Execute a command with parameters and return a bytestring with the result.subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

We could see that the method accepts the same arguments as the call() method, except for universal newlines. Whenever set to true, this boolean argument accesses files containing stderr and stdout on a global newline.

Furthermore, the procedure returns the same result as the call() method. Consider again a simple example. The echo instruction on Linux is used once to emit the input that comes with the command. The result of the echo statement is stored in a string parameter and printed using the print function in Python.

Code

# import the subprocess moduleimport subprocess# declare stringstr = subprocess.check_output(["echo", "Hi Java point"])# use the print function to display print(str).

Exit

B' ” Hello Java dot ” \r \n '

popen method

A calling method update function is known as the Popen function. The command specified by the string command is executed by the popen() method. The method must establish a connection between the calling program and the completed command and return a reference to a stream that can be used for reading and writing. The popen function initializes and returns data; therefore, it does not wait for the subprocess to complete.

Code

# import subprocess moduleimport subprocess# declare the processp = subprocess.Popen(['echo','" Hi Java Point"'],stdout = subprocess.PIPE,shell=True)result = process.communicate()[0]# show o resultado repr (resultado)

Exit

'b\'" \\\\" hello java dot \\\\"" \\ r \\ n\"

The Popen function constructor

The Popen class controls the module's primary build process, the Popen build. It offers a variety of features, allowing developers to deal with unusual situations that are not fully covered by the offerings.

security aspects

Unlike some others, this method will never launch a system shell dynamically. Now child processes can receive any characters, especially shell metacharacters, without risk. The application is responsible for ensuring that almost all whitespace, including meta-symbols, are properly quoted when specifically invoking shells with the Shell=True flag. This prevents the Python subprocess from having shell injection issues. On some systems you can use this escape with shlex.quote().

Exceptions in the subprocess

Just before the new program is executed, the errors are described as described in the Python Subprocess function call and thrown back into the parent program. The most common error is called OSError. Remember something when shell=True that the child would throw an OSError only if the selected shell somehow could not be found. It is necessary to examine the return code or results of the subprocess to see if the shell did not find the program you want.

Past shell enforcement functions

Functions from the old 2.x instruction module are also provided by the subprocess in the Python language. These actions imply starting the system shell and correspond to exception handling.

In this post, we covered Python subprocesses. It's now easy to start other processes from Python code using the subprocess module. The two main operations of this module are call() and pippen(). After practicing and learning to use these two methods correctly, users will have no problem creating and deploying subprocesses in Python.

Diploma

A subprocess is an artificially generated computing process. Tools like device manager and htop allow us to monitor the processes that are active on our computer. Python subprocess library is available. Currently, the Run method provides a straightforward interface for configuring and controlling subprocesses. Since we connect directly to the operating system, we can create any type of application with them.

Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated: 12/18/2022

Views: 6812

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.