如何在没有路径的情况下运行python文件? [英] How do I run python file without path?
问题描述
为了避免输入长路径名,我试图创建一个文件夹来放置我所有的 .py 文件.我希望它是某种默认"文件夹,每次运行 .py 文件时,系统将搜索此文件夹以查找该文件.
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.
我想到的一个解决方案是将我的 .py 文件放在像python\lib"这样的模块文件夹中,我可以调用 python -m 文件名.
One solution i figured, is to put my .py file in those module folders like "python\lib", and I can call python -m filename.
但我不想把lib文件夹弄得一团糟.
But I do not want to make a mess in the lib folder.
还有其他方法吗?谢谢!
Is there any other ways to do it? Thanks!
推荐答案
我假设您在 Windows 上运行 Python('\' 反斜杠是我唯一的线索).如果是这样,我认为您至少有一个合理的选择.
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.
创建一个类似这样的python_run.bat文件:
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
然后确保python_run.bat所在的文件夹在你的PATH
环境变量.因此,如果脚本位于 C:\Path\To\Scripts\python_run.bat
,您需要确保您的 PATH
环境变量具有 C:\Path\To\Scripts
在其中.
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.
然后您只需键入以下内容即可执行位于 SCRIPT_DIR 中的任何脚本.
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
这篇关于如何在没有路径的情况下运行python文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!