简体   繁体   中英

How do I run python file without path?

To avoid type in long path name, I am trying to create a folder to put all my .py file in. And I want it to be some sort of "default" folder that every time I run .py file, the system will search this folder to look for that file.

One solution i figured, is to put my .py file in those module folders like "python\\lib", and I can call python -m filename.

But I do not want to make a mess in the lib folder.

Is there any other ways to do it? Thanks!

I'm assuming you're running Python on Windows (the '\\' backslash is my only clue). If so, I think you've got at least one reasonable option.

Create a python_run.bat file similar to this:

@ECHO OFF

REM *** MODIFY THE NEXT LINE TO SPECIFY THE LOCATION OF YOUR SCRIPTS ***
SET SCRIPT_DIR=C:\Path\To\Scripts

REM *** MODIFY THE NEXT LINE TO SPECIFY THE LOCATION OF YOUR PYTHON.EXE ***
SET PYTHON_BIN=C:\Python27\python.exe

PUSHD %SCRIPT_DIR%
%PYTHON_BIN% %*
POPD

Then make sure the folder where the python_run.bat is located is in your PATH environment variable . So if the script lives in C:\\Path\\To\\Scripts\\python_run.bat , you'd make sure your PATH environment variable had C:\\Path\\To\\Scripts in it.

Then you simply have to type the following to execute any script located in your SCRIPT_DIR.

python_run my_cool_script.py --foo=bar

And it will result in running the following command as if you were already inside your scripts folder:

C:\Python27\python.exe my_cool_script.py --foo=bar

for example: first type

sys.path.append("/home/xxx/your_python_folder/")

then you can import your own .py file

It's not possible to do that without path. The only thing that you can is putting all of modules that you want to use in the same directory, you don't have to put them python\\lib , you can put them in a folder on your desktop for example.Then run your scripts in that folder but, always be sure starting scripts with #!/usr/bin/env python .

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