简体   繁体   中英

Launch Python script from windows command line using system PATH for file location

This may be more of a general Windows question than a Python question, I'm not sure.

I have a folder full of python files called GDAL (a geospatial library). The location of the GDAL library is stored in the windows system PATH, so when I type this in a windows command window to check PATH is configured correctly:

gdal_retile.py

I get notepad opening to show the code, as I would expect, as this is the default application for .py files on this pc.

If however I do this:

python gdal_retile.py

It doesn't work, it says

no such file or directory

Yet if I define the full path:

python "C:\Program Files\GDAL\gdal_retile.py"

It works fine. Can't PATH be used as part of an argument to the Python interpreter?

TL:DR; No.

PATH is used to search for the (executable) file you're trying to run. If a file is not executable (eg, text files), windows will try to look up which program is registered to handle the file's extension (in your case notepad) an open that one, passing the file's path as argument to it.

Once the correct program has been found, all the following arguments are first checked for eventual %ENVIRONMENT_VARIABLE% placeholders to replace with the actual values, then treated as a list of space-separated strings and passed to the program starting. It's the program's task, then, to figure out what to do with them. PATH has no play in the arguments resolution.

Why is it so?

Arguments to a program can be anything. Imagine you're passing the filename of a file you want to create in the current folder. How can the OS know that the filename you're passing in is not actually an existing file to be searched for in PATH , but a file that will be created by the program? That's why the responsibility to handle arguments is entirely on the program that is being started.

Python doesn't consider system path in its arguments, not even PYTHONPATH ...

You can simulate this using where to find the script in the path

where gdal_retile.py > %TEMP%\fullp

then use that to set a variable

set /P C=<%TEMP%\fullpath

then call python with the full path

python "%C%"

(there's no error checking here on the where command, which could return nothing or more than 1 path, so that solution is perfectible but convenient to launch another interpreter than the one associated with the .py extension on Windows)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM