[英]Why does my python not add current working directory to the path?
I keep seeing sites mentioning that the directory that you execute 'python ' get added to the python path.我一直看到网站提到您执行 'python' 的目录被添加到 python 路径中。 For example on http://www.stereoplex.com/blog/understanding-imports-and-pythonpath , the author cd's to the /tmp folder then does 'print(sys.path)' and lo and behold, the /tmp folder appears in the path list.例如在http://www.stereoplex.com/blog/understanding-imports-and-pythonpath 上,作者 cd 到 /tmp 文件夹然后执行 'print(sys.path)' 并且瞧,/tmp 文件夹出现在路径列表中。 Here is me trying this out on my system (with 2.6.6 installed):这是我在我的系统上尝试这个(安装了 2.6.6):
example structure:示例结构:
app/
mymodule.py
inner_folder/
myscript.py
in myscript.py contains the line:在 myscript.py 中包含以下行:
import mymodule.py
what I did:我做了什么:
cd app
python inner_folder/myscript.py # ImportError
Since I am executing the interpreter from the app/ directory, shouldn't 'app' be added to the python path?由于我是从 app/ 目录执行解释器,所以不应该将“app”添加到 python 路径中吗? This is how a lot of the docs I have been reading have specified the behaviour should be.这就是我阅读的许多文档都指定了行为应该是怎样的。
Please enlighten!请赐教!
(I have temporarily solved this by manually adding the folder I want into the environment but don't want to rely on that forever. Since many sites say this can be done, I'd like to reproduce it for myself) (我通过手动将我想要的文件夹添加到环境中暂时解决了这个问题,但不想永远依赖它。由于许多网站都说可以做到这一点,我想自己复制它)
It is the script's directory that is added, not the current directory.添加的是脚本的目录,而不是当前目录。 If you turn inner_folder/
into a package then you can use python -m inner_folder.myscript
in order to run the script while having app/
added to sys.path
.如果将inner_folder/
转换为包,则可以使用python -m inner_folder.myscript
来运行脚本,同时将app/
添加到sys.path
。
Whether or not the current directory is in sys.path
, import statements usually look like:无论当前目录是否在sys.path
,import 语句通常如下所示:
import mymodule
The code you wrote looks like:您编写的代码如下所示:
import 'mymodule.py'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.