1

I would like to use a python script anywhere within command prompt. This is possible in unix, but I couldn't find anything for windows. Do I have to convert it to .exe?

Edit: not sure why this is being downvoted, maybe it's a silly question but I can't find any similar threads here and I can't be the first person to want to execute .py scripts from their path...

Edit 2: I think my wording was unclear. I would like to know a method to execute python scripts in Windows without needing to specify python path/to/script.py every time. Here is a solution on Linux where the shebang statement invokes the python interpreter, and the script in question can be easily placed in bin: How do I install a script to run anywhere from the command line? . Does there exist a solution like this for Windows?

Null Salad
  • 765
  • 2
  • 16
  • 31
  • A Python script is a text file. On Windows you can run it by opening it with the `python.exe` executable (or with a text editor if you want to edit it). In a command prompt you would use `python script.py`. See https://docs.python.org/3.6/using/windows.html. – user2314737 Feb 11 '18 at 09:40
  • I know that you need to use python to run it, I was wondering if there was a way to do this without needing to go `python path/to/script.py` everytime – Null Salad Feb 11 '18 at 09:47
  • Edit: similar solution for linux https://superuser.com/questions/828737/run-python-scripts-without-explicitly-invoking-python – Null Salad Feb 11 '18 at 09:53

1 Answers1

3

Here's a solution for running myScript.py:

  1. add to the myScript.py file a first line #!python (or #!python3 if you want to use Python 3)

For instance:

#!python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
  1. change the "opens with" property of myScript.py to py.exe (to find where it is use where py-- I have it in C:\Windows\py.exe)

  2. put the script myScript.py somewhere in your Windows path

and now you should be able to type myScript.py anywhere in a command prompt and run the Python script with your chosen Python version.

See: https://docs.python.org/3.6/using/windows.html#from-the-command-line

user2314737
  • 27,088
  • 20
  • 102
  • 114
  • Awesome this works! Though I cannot import 3rd party modules installed with pip when I run the script from cmd. Any ideas as to why? – Null Salad Feb 11 '18 at 11:24
  • @NullSalad maybe you are mixing the versions, if you installed modules for Python2 they won't be available for Python3 and you need to install another copy with `pip3` – user2314737 Feb 11 '18 at 11:29