Running python scripts from DOS or python shell without path name
I was att开发者_运维技巧empting to edit the registry so when I type into either the python shell or a DOS window:
python sample.py
I want it to go to the directory that I save my .py files to and run the file without me having to type:
python C:\PythonPractice\sample.py
any ideas?
For the DOS window:
set VARIABLE=yourpath
python %VARIABLE%\sample.py
So for your example you could do this:
set p=C:\PythonPractice
python %p%\sample.py
You can setup this permanently by going to "Control Panel">>"System">>"Advanced system settings">>"Environment Variables". You probably want to add a variable to your account, unless you want it to affect all of the system profiles. A restart is probably required.
@echo off
c:
CD c:\py
c:\python271\python.exe %1
Save that as py.bat
in a dir on your PATH
. Change c:\py to the directory of your scripts.
You can call your scripts from everywhere like this:
C:\Windows>py hallowelt.py
Hallo!
A slight improvement to Jacob's answer:
@echo off
pushd c:\py
c:\python271\python.exe %*
popd
Save this as py.cmd in one of the directories from your your PATH environment variable. Then you can call
py sample.py arg1 arg2 ...
This works with any number of arguments.
But, as wberry mentioned, you could change the working directory from inside your Python script as well, if you really need to (but I think that's a bad idea):
os.chdir(os.path.abspath(os.path.dirname(__file__))) #untested
While this isn't exactly an answer to your question, I recommend using the following pattern: Say, I have a Python script c:\mydir\myprog.py that requires special environment variables (PATH, ORACLE_HOME, whatever) and maybe it needs a particular working directory.
Then I create a file myprog.cmd in the same directory:
@echo off
setlocal
set PATH=...
set ORACLE_HOME=...
pushd %~dp0
python %~dpn0.py %*
popd
endlocal
The pushd/popd part is for changing and restoring the working directory.
For an explanation of the %~... Syntax, type
help call
at the command prompt.
This approach gives you full control about the environment of your Python program. Note that the python call is generic: If you need a second Python script otherprog.py, then just save a copy of myprog.cmd as otherprog.cmd.
精彩评论