rolisz's site

Redirecting Python output from the command line

Today I needed to write a quick script that does some operations on colors. Because I'm trying to learn Vim and I'm trying to master the command line (not the standard Windows one, but Console2 + PyCmd), of course I wrote it with command-line usage in mind. The script starts taking shape, so let's use it. Well, it prints out the desired output. What next? Let's redirect its output to the clipboard. A quick Google search revealed the clip utility, which copies to the clipboard its stdin.

colors.py middle #000 #FFF | clip

Some­thing's wrong - pasting won't work. The output shows up ok in the console, but it won't redirect - to a file either.

After some googling, I found that someone had a similar problem - and he had received an answer on Stack­Over­flow. The problem apparently is with trying to launch scripts from a file as­so­ci­a­tion, without explicitly naming the program. For example, using python colors.py middle #000 #FFF | clip worked. Microsoft is aware of the problem and released a hotfix for it, but only for Windows 2000 and Windows XP, so Windows 7 users have to fix it on their own.

Making it work without writing python in front of the command required editing the registry.

Open up regedit.exe, export your registry to back it up, then browse to HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPolicies Explorer. Right-click and create a new DWORD (32 bit) value called InheritConsoleHandles. Double-click on it and set its value to 1.

Restart your console and voila, output redi­rec­tion should work.

I think this applies to other languages too, such as Ruby or Perl.