0

I have written a lot of code that relies on output redirection in cygwin.

I now have to integrate some libraries that aren't compatible with cygwin and that need in my case Windows or Linux.

Is there a smooth way to go from cygwin's python script.py 42 <in.txt >out.txt to powershell's equivalent? I know powershell can't use input/output redirection, at least not with the <, > (the documentation says it can weirdly) but is there another way?

SwimBikeRun
  • 4,192
  • 11
  • 49
  • 85

1 Answers1

1

PowerShell definitely can do input/output redirection, it just doesn't do it the exact same way as bash.

I'm assuming you don't want to actually learn PowerShell, just get a quick & dirty answer. So, here goes.


For simple cases, bash-like syntax works fine:

foo > out.txt

When that doesn't work, often just wrapping up the tool in Powershell scriptlet is all you need. In other words, create a foo.ps1 file with this in it:

foo > out.txt

Then just run foo.ps1 instead of foo.


You may also want to look at the Tee-Object, Set-Content, Add-Content, and Start-Transcript, etc. cmdlets. Start with A Task-Based Guide to Windows PowerShell Cmdlets.

For example, Start-Transcript captures standard output as a "dumb string" and writes it to a file. So, one equivalent of foo > out.txt is:

Start-Transcript -path out.txt
foo
Stop-Transcript

Or, for foo >> out.txt:

Start-Transcript -path out.txt --append
foo
Stop-Transcript

Similarly, in the other direction, Get-Content reads a text file and prints it out as a dumb string, which you can pipe to your program:

Get-Content in.txt | foo

Of course another obvious possibility is to change your Python script to take filenames.

In many cases, just using fileinput.input() instead of sys.stdin gives you this for free—you can pass it a file's content via stdin, or a filename on the command line (or all kinds of fancier combinations) and the script will see it the same way.

abarnert
  • 354,177
  • 51
  • 601
  • 671