Learn to Code by Solving Problems: A Python Programming Primer Homepage for the book Learn to Code by Solving Problems: A Python Programming Primer

Input and Output Redirection in PowerShell

Hello!

If you’re trying to use input redirection in Chapter 2 with PowerShell, you’ll need a different approach than the < operator that works in many other shells.

Let’s say you wanted to use input redirection on the Telemarketers problem in Chapter 2. Here’s the command that I’m currently using for PowerShell for input redirection:

Get-Content telemarketers_input.txt | python telemarketers.py

Get-Content reads the contents of a file. The | symbol instructs PowerShell to pipe that content to the command on the right, which is Python running your telemarketers program.

For output redirection, try this:

python telemarketers.py | Set-Content telemarketers_output.txt

This time, Python is on the left of the | and the | symbol is piping the output to Set-Content. As always with output redirection, be careful that you don’t overwrite an important file!

OK – now both input redirection and output redirection at the same time? You got it:

Get-Content telemarketers_input.txt | python telemarketers.py | Set-Content telemarketers_output.txt

Here, Get-Content is getting stuff from a file and sending it to Python, and Set-Content is taking stuff from Python and sending it to a file.