# 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)
```
