Python subprocess run multiple commands

“`html

Explanation:

In Python, the subprocess module provides a way to spawn new processes and execute system commands. The `run` function from the subprocess module can be used to run multiple commands sequentially.

Example:

Let’s say we want to run two commands using the `subprocess.run` function:

  • Command 1: `ls -l` – list files and directories in long format
  • Command 2: `pwd` – print current working directory

To achieve this, we can use the `subprocess.run` function twice:

    
      import subprocess
      
      # Command 1
      result1 = subprocess.run(['ls', '-l'], capture_output=True, text=True)
      
      # Command 2
      result2 = subprocess.run(['pwd'], capture_output=True, text=True)
      
      print(result1.stdout)
      print(result2.stdout)
    
  

In this example, we import the `subprocess` module and then invoke the `run` function twice.

For each `run` function call, we provide the command as a list of strings. The `capture_output=True` argument is used to capture the output of the command, and `text=True` is used to decode the output as a string.

The `subprocess.run` function returns a `CompletedProcess` instance, which contains information about the command execution. In this example, we print the output of each command using the `stdout` attribute.

By running the above code, you should see the list of files and directories in long format printed first, followed by the current working directory.

Note: Make sure to adjust the commands based on your operating system.

“`

Leave a comment