简体   繁体   中英

Run python scripts from any folder under powershell in windows

I have a folder of python scripts which I'd like to run from any folder under windows. As a python interpreter I am running Python 3.6 installed with Miniconda.

For example in the folder C:\\Users\\name\\my_scripts I have a script called test.py with the following content.

print('test')

After navigating to the folder running the script works by executing it with python producing the following output.

PS C:\Users\name\my_scripts> python test.py
test

PS C:\Users\name\my_scripts> cd..
PS C:\Users\name> python test.py
C:\Users\name\Miniconda3\python.exe: can't open file 'test.py': [Errno 2] No such file or directory

I tried adding C:\\Users\\name\\my_scripts to Path . Typing test.py in any folder in powershell opens the script with my default text editor, but executing the script with python test.py form anywhere but the script folder results in a file not found error.

Creating a %PYTHONPATH% environment variable containing the script folder did not work neither. As far as I understand the this is normal as this environment variable is supposed to be used to import modules from specific locations, but not to execute modules by themselves.

Is there a way to execute the scripts in the my_scripts folder from any given location?

python my_scripts\\test.py should work.

More generally, you run a python script using the interpreter with: python PATH_TO_SCRIPT

I think you can do it 3 different ways:

  • python ./path/to/script
  • make a package of your files, ie .whl file, and pip install it (it works although the conda environment warns you from doing pip installs)
  • make your own .bat file where you cd into the script folder before starting python, the .bat file you can place in ./Miniconda/Scripts and it will work when you start your conda prompt

there is one way left, but that's quite ugly and not recommended, but it works. first find out which folder are in sys.path in a python session, then just copy the your_script.py to a folder there. You can then get a hold of that script by doing python -m your_script.py It will complain that your_script is not a module, so therefore not recommended, but a quick way forward if that's what your're looking for.

hm, it sounds like you really should do a .bat file. maybe name it mp.bat in that .bat you can do the cd, and also parse cmd line options, so your ps line could simply be: mp.bat test.py which seems to be what you are looking for, a bit of googling and I'm sure you will find out how to take arguments into a .bat file

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