简体   繁体   中英

How can I add a python script to the windows system path?

I'm using windows cmd to run my python script. I want to run my python script withouth to give the cd command and the directory path. I would like to type only the name of the python script and run it.

I'm using python 2.7

1.Go to Environmental Variables > system variable > Path > Edit

2.It look like this

Path C:\\Program Files\\Java\\jdk1.8.0\\bin;%SystemRoot%\\system32;C:\\Program Files\\nodejs\\;

3.You can add semicolon (;) at the end and add C:\\Python27

4.After adding it look like this

C:\\Program Files\\Java\\jdk1.8.0\\bin;%SystemRoot%\\system32;C:\\Program Files\\nodejs\\;C:\\Python27;

Create batch file inside the script's directory.

@echo off
echo.
python %~dp0\<script-name>.py %*

Put the above lines inside of it. And change according the script you want to run.

" %~dp0 " is unique variable witch returns batch file's directory.

" % *" are the arguments passed through.

os.chdir(os.path.dirname(sys.argv[0]))

Also put the above line inside the script. The code above changes your python script's working directory to it's own directory. "sys.argv[0]" always returns path of the script itself.

And add your script to Enviroment Variables. And run from command prompt using the batch file's name.

Make sure .py files are associated with the Python launcher C:\\Windows\\py.exe or directly with eg 'C:\\Python27\\python.exe then edit your PATHEXT environment variable using (System Properties) to add ;.PY` at the end. You can now launch Python files in the current directory by typing their name.

To be able to launch a given Python script from any directory, you can either put it in a directory that's already on the PATH , or add a new directory to PATH (I like creating a bin directory in my user folder and adding %USERPROFILE%\\bin to PATH) and put it there.

Note that this is more a "how do I use Windows" question rather than a Python question.

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