Python sys.path修改不起作用 [英] Python sys.path modification not working

查看:374
本文介绍了Python sys.path修改不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改我的一个Python文件中的sys.path以便拥有一些 模块搜索路径中的特定库目录(可能不是最好的方法) 但 ...).如果我在sys.path的前面插入几个路径,我的脚本将不会考虑这些路径以用于将来的导入.如果我制作了一个包含我需要的库的新列表,并将该列表分配给sys.path,则将这些导入考虑在内.这是正确的行为吗?我正在使用python 2.5.4.可能是由于我的环境导致这种行为吗?

一些代码段: 如果我做

这没用.它不考虑路径.

如果我愿意

可以.

谢谢

解决方案

您确实需要发布一些代码来帮助我们.但是,我可以做出有根据的猜测.您说如果创建一个完整的新列表并将其分配给sys.path,那么它将起作用.我想你是说你在做这样的事情

sys.path = ["dir1", "dir2", ...]

但是,如果您在开始处插入路径,那么它将不起作用.我的猜测是您正在使用insert方法,就像这样

sys.path.insert(0, ["dir1", "dir2"])

如果是,那么这是不正确的.这将创建一个看起来像

的列表

[["dir1", "dir2"], "dir3", ...]

您应该说

sys.path[:0] = ["dir1", "dir2"]

这会给你

["dir1", "dir2", "dir3", ...]

但这只是猜测,直到您发布代码.

I'm trying to modify the sys.path in one of my Python files in order to have some specific libraries dirs in the modules search path (it might not be the best way but ...). If I insert several paths in the front of sys.path my script is not taking into account those paths for future imports. If i make a whole new list containing those libraries dirs i need and assign that list to sys.path then those imports are taken into account. Is this the correct behavior? I'm using python 2.5.4. Could it be something from my environment that could lead to such behavior?

Some code snippets: If I do

pathtoInsert1 = " .... "
pathtoInsert2 = " .... "
sys.path.insert(0, pathToInsert1)
sys.path.insert(0, pathToInsert2)

it does not work. It does not take into account the paths.

If I do

pathList = [pathToInsert1, pathToInsert2] 
sys.path = pathList

it works.

Thanks

解决方案

You really need to post some code for us to be able to help you. However, I can make an educated guess. You say that if you make a whole new list and assign it to sys.path then it works. I assume you mean that you're doing something like this

sys.path = ["dir1", "dir2", ...]

But that if you insert the paths at the beginning then it doesn't work. My guess is that you're using the insert method, like so

sys.path.insert(0, ["dir1", "dir2"])

If so then this is incorrect. This would create a list that looks like

[["dir1", "dir2"], "dir3", ...]

You should instead say

sys.path[:0] = ["dir1", "dir2"]

which will give you

["dir1", "dir2", "dir3", ...]

But this is all guesswork until you post your code.

这篇关于Python sys.path修改不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆