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
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]" 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 e.g. 'C:\Python27\python.exethen edit yourPATHEXTenvironment 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.
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;
python script_name.pyfrom any where in the command prompt?