Running Python scripts through the Windows Command Line

15,488

From the book (p. 44, 4th Ed):

Finally, remember to give the full path to your script if it lives in a different directory from the one in which you are working.

For your situation, this means using

C:\User\Example> python C:\User\Example\my_scripts\script1.py

You could write a batch file that looks for the script in a predefined directory:

@echo off
setlocal
PATH=C:\User\Example\Python36;%PATH%
SCRIPT_DIR=C:\User\Example\my_scripts
python %SCRIPT_DIR\%*
Share:
15,488
Alden Bernitt
Author by

Alden Bernitt

Updated on June 04, 2022

Comments

  • Alden Bernitt
    Alden Bernitt almost 2 years

    I've just started learning Python using Learning Python by Mark Luts. In his book he offers an example of a simple script that is called through the Windows shell. In the example, he calls is as follows:

    C:\code> python script1.py
    

    I've gone and modified the Environment Variables on my machine so that I can call

    C:\User\Example> python
    

    to open up the interpreter and I can also call something like

    C:\User\Example> script1
    

    to run a script that I've written and placed in my desired directory. My issue is that I can not call

    C:\User\Example> python script1.py
    

    in my command line the same way he does in the book. He's mentioned something about a PYTHONPATH Environment Variable, however, this variable isn't present on my machine. I only have 'path', 'TEMP', and 'TMP'. Particulary, when I try to make such a call I get the error

    python: can't open file 'script1.py': [Errno 2] No such file or directory
    

    What do I have to do in order to get this sort of command to work properly on the command line?