我想运行:
python somescript.py somecommand
但是,当我运行这个我需要PYTHONPATH
包括某个目录。我不能只是把它添加到我的环境变量,因为目录我要添加基于我跑什么项目的变化。有没有办法来改变PYTHONPATH
运行脚本时?注:我甚至不具有PYTHONPATH
可变的,所以我并不需要担心追加到它的VS这个脚本运行期间覆盖它。
对于Mac / Linux的;
PYTHONPATH=/foo/bar/baz python somescript.py somecommand
对于Windows,安装的包装pythonpath.bat
;
@ECHO OFF
setlocal
set PYTHONPATH=%1
python %2 %3
endlocal
并调用pythonpath.bat
脚本文件等;
pythonpath.bat /foo/bar/baz somescript.py somecommand
import sys
sys.path.append('your certain directory')
基本上sys.path是所有为Python模块搜索的路径列表。它被解释初始化。 PYTHONPATH的内容自动添加到列表的末尾。
如果您正在从一个兼容POSIX的shell命令,就像bash
,你可以这样设置环境变量:
PYTHONPATH="/path/to" python somescript.py somecommand
如果这一切都在同一行,PYTHONPATH环境值仅适用于一个命令。
$ echo $PYTHONPATH
$ python -c 'import sys;print("/tmp/pydir" in sys.path)'
False
$ PYTHONPATH=/tmp/pydir python -c 'import sys;print("/tmp/pydir" in sys.path)'
True
$ echo $PYTHONPATH
你可以试试这个执行你的脚本里面的函数
python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"
这是Windows:
例如,我有一个名为“mygrapher”我的桌面上的文件夹中。内部,有文件夹名为“计算”和“图形”包含我的主文件“grapherMain.py”需要Python文件。此外,“grapherMain.py”存储在“图形”。要运行在不移动文件的一切,我可以做一个批处理脚本。让我们把这个批处理文件“rungraph.bat”。
@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal
该脚本位于“mygrapher”。要运行的东西,我会进入我的命令提示符,然后执行:
>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)