简体   繁体   中英

run python scripts from anywhere in the filesystem in windows

I've implemented some utility for my needs to simplify the development using Python. It requires multiple .py files and some additional .template files - renamed .txt file.

I want to have an ability to use this utility from anywhere in the filesystem. For example if I am currently in some folder I want to run something like

 >python util1.py

And get the required result in the current folder.

How to do it?

If it's not possible is there a way to create one module with .py scripts and .template files and then take it with me anywhere?

If I put it into PYTHON_HOME aka D:\\Python27 it shows error

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

If I put it into C:\\Windows it doesn't work either.

运行setx path "%path%;C:\\path\\to\\util.py" ,您应该会很好。

As for your scripts, put them in a directory and add that directory to your PYTHONPATH environment variable .

For example,

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

I'm assuming that the .template files are read by your script? In that case, hardcode their location in your script (if you don't, the script will look for them in your current directory).

with open(r"C:\My_templates\foo.template") as footemp:
    # do something

Now if you cd to any directory and run python.exe util.py , Python will find util.py because it's in the Python path. Its import s will also use that path and therefore succeed as well. If your script opens template files, it will find them because their location is specified. And if your script writes files, it will do so in the current directory.

您可以将util1.bat文件放入C:\\Windows ,其中包含: python path_to_util1\\util1.py %*

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