# 155. Subprocess Management with subprocess

Here are 10 Python snippets demonstrating subprocess management with the `subprocess` module for running system commands and interacting with external processes. Each snippet is separated by a delimiter.

***

**Snippet 1: Running a Simple Command**

```python
import subprocess

result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print("Output:", result.stdout)
```

***

**Snippet 2: Capturing Errors**

```python
import subprocess

result = subprocess.run(['ls', 'non_existent_directory'], capture_output=True, text=True)
print("Error:", result.stderr)
```

***

**Snippet 3: Checking Command Success**

```python
import subprocess

result = subprocess.run(['ls'], capture_output=True, text=True)
if result.returncode == 0:
    print("Command succeeded")
else:
    print("Command failed with return code:", result.returncode)
```

***

**Snippet 4: Running a Shell Command**

```python
import subprocess

result = subprocess.run('echo $HOME', shell=True, capture_output=True, text=True)
print("Home Directory:", result.stdout.strip())
```

***

**Snippet 5: Redirecting Output to a File**

```python
import subprocess

with open('output.txt', 'w') as file:
    subprocess.run(['echo', 'Writing to a file'], stdout=file)
print("Output written to 'output.txt'")
```

***

**Snippet 6: Passing Input to a Command**

```python
import subprocess

result = subprocess.run(['cat'], input="This is input text\n", text=True, capture_output=True)
print("Command Output:", result.stdout)
```

***

**Snippet 7: Running a Command Without Waiting for Completion**

```python
import subprocess

process = subprocess.Popen(['sleep', '5'])
print("Process started with PID:", process.pid)
```

***

**Snippet 8: Communicating with a Process**

```python
import subprocess

process = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
stdout, _ = process.communicate("This is sent to stdin")
print("Output from the process:", stdout)
```

***

**Snippet 9: Running Multiple Commands Sequentially**

```python
import subprocess

subprocess.run(['echo', 'First Command'])
subprocess.run(['echo', 'Second Command'])
```

***

**Snippet 10: Using `subprocess.PIPE` for Real-Time Output**

```python
import subprocess

process = subprocess.Popen(['ping', '-c', '4', 'google.com'], stdout=subprocess.PIPE, text=True)
for line in process.stdout:
    print(line.strip())
```

***
