# Python - subprocess for Windows

## Getting Start

```python
import subprocess
subprocess.call("dir", shell=True) #Run under Windows 
```

## How to use "|" command

Below showing the example for running command "dir | findstr py", the trick here is using stdin and stdout params to chain them up.

```python
import subprocess
command1 = subprocess.Popen(['dir'],
                        shell=True,
                        stdout=subprocess.PIPE,
                        )
command2 = subprocess.Popen(['findstr', 'py'],
                        stdin=command1.stdout,
                        shell=True,
                        stdout=subprocess.PIPE,
                        )
end_of_pipe = command2.stdout
for line in end_of_pipe:    
    print('\t', line.strip())
```

## Interactive way to print the output

The above example relies on process completion as a event of triggering the print output. However, how to print the stdout in more interactive way?&#x20;

```python
import subprocess, sys
proc = subprocess.Popen(['ping', '8.8.8.8', '-t'],
                        shell=True,
                        stdout=subprocess.PIPE,
                        )
while True: # Infinite loop
    output = proc.stdout.readline()
    if proc.poll() is not None:
        break    
    if output:
        print(output.strip())
```

## Windows Constants (Flags)

It is quite important to explore the topic of Windows Constants (flags) from using subprocess in Windows environment. IMO, subprocess is more POSIX friendly, there are functions are only supporting on Unix environment. If you want to achieve some similar features on Windows, you may need to read through what **Flags** available for you.

Here is the example of how to apply flags into your program using **creationflags** attribute on **Popen()**

```python
_proc = subprocess.Popen(command, creationflags=subprocess.DETACHED_PROCESS)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ph20eow.gitbook.io/tech-stuff/python-subprocess-for-windows.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
