views:

631

answers:

6

I have a python script that i want to run from the command line but unsure how to run it. Thanks :)

+3  A: 

python myscript.py

Joey
+1  A: 

See Basic Hints for Windows Command Line Programming.

If your python installation directory is included in %PATH% -

C:\> python myscript.py

If you know the installation path:

C:\> C:\python26\python myscript.py

And, you can insert a hashbang in the 1st line of the script:

#! C:\python26\python

and it will run by typing just the script name. This is the content of p.py:

#!C:\python26\python
import sys
print sys.path

And calling it directly from a cmd.exe window:

C:\>p.py
['C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs',
'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win',
'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 
'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib]
gimel
Oops, deleted my comment. I was asking what Johannes answered. SilentGhost's answer makes gimel's hashbang variant work, I guess, though it does work because of the extension and not because of the hashbang.
OregonGhost
Works on my windows installation of python2.6.
gimel
+2  A: 

If your script is foo.py, you can simply do

C:\Python25\python.exe foo.py

Assuming you have python 2.5 installed in the default location. Alternatively, you can add C:\Python25 to your %PATH%, so that:

python foo.py

will work. But be aware that changing %PATH% may affect applications (that's why it is not done by the python installer by default).

David Cournapeau
+3  A: 

I do it this way:

C:\path\to\folder> yourscript.py
SilentGhost
This works great if you have the Python interpreter as the default program to open .py files.
Paul Fisher
isn't it what installer does by default?
SilentGhost
@SilentGhost: the user may want to open Python files in an editor by default.
Bastien Léonard
Executing the script is default behaviour for .js and .vbs files as well on Windows, so it's at least following the convention ;)
OregonGhost
A: 
  1. do you have python installed? if not install it from python.org
  2. on command line use

    python "path to script.py"

  3. if python is not in PATH list you can add it to PATH in environment variables or directly use path to python.exe e.g.

        c:\python25\python.exe myscript.py
    
Anurag Uniyal
A: 

You might find it useful to include a .bat file which calls the .py script. Then all you need to do is to type the name of your script to run it.

Try something like: python %~dp0\%~n0.py %*

(From http://wiki.tcl.tk/2455)

Andy