Running Python Scripts Inside Windows Power Shell

I took a big leap and decided that I was going to trade in cygwin for Windows Power Shell. Well, at least that’s the theory. We’ll see how it actually goes in the long run.

Anyway, I have quite a few python scripts that I was using, which I can pretty easily port to native Windows Python. But of course I want to be able to run them inside of WPSH.

Assuming a script named “tst.py” in the current working directory, I tried a variety of things to make this happen:

  • Just type in the name of the file “./tst.py”. This zapped up a new command window and ran the python script in it. This is not very useful because I really need to see the output. (Note: If you do this inside of a command shell the behavior is correct.)
  • Rename the file from “tst.py” to “tst.pyw” so that pythonw.exe will be used to run it. Also a no go. I got no new command window, but also no stdout to the WPSH.

Those were the obvious things to try. So I began to search, and found references to IronPython and how to run it inside of WPSH. That and a variety of other things, but nothing that solved my actual problem. (i.e. got my current python scripts to run correctly in WPSH).

Now, if I run python itself from WPSH I get a python prompt from where I can do python stuff. So I tried typing “python tst.py” in WPSH and viola I saw my output.

Since that worked I went ahead and defined the following:

function tst { python tst.py $args}

Given that I have a new WPSH function that calls python on the file “tst.py” and passed through the args. This has the behavior I was looking for. The big downsize here is that I have to write a WPSH wrapper function for each of my python scripts, but I have only about a dozen so that’s what I’m going to do. I am not 100% satisfied with the soluton, but it’s good enough for now.

Update:

I found a better way to do this here. Essentially put:

@setlocal enableextensions & python -x "%~f0" %* & goto :EOF

At the top of your script.

Here’s a full example, the file is named cg.cmd.

@setlocal enableextensions & python -x "%~f0" %* & goto :EOF

from devtools.codegen.api import cg_main

if __name__ == "__main__":
   cg_main()

 

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: