在python脚本中加载新安装的模块
我正在编写一个 python 脚本,它自动设置 django Web 服务器环境。
在脚本中,我正在使用安装新模块
for package in packages:
os.system("%s %s" % ('easy_install', package))
这工作正常。我唯一的问题是我想在同一个脚本中使用这些新安装的包,
package = __import__(package)
但这不起作用,并且我收到一个 ImportError: No module named reportlab (for example)
如果我再次运行该脚本,该脚本将像我一样工作假设所有新安装的软件包都位于系统路径上。我希望有一种方法可以在不重新启动脚本的情况下导入新模块。
我尝试重新加载(sys)但它没有帮助我。我可以通过手动附加到 sys.path 或使用 os.system() 启动新的 python 脚本来破解它,但我更喜欢更干净的解决方案。
I am writing a python script which automatically sets up a django web server environment.
In the script, I am installing a new modules using
for package in packages:
os.system("%s %s" % ('easy_install', package))
This works fine. My only issue is that I want to use these newly installed packages in the same script using
package = __import__(package)
This does not work though, and I receive an ImportError: No module named reportlab (for example)
If I run the script again, the script works as I assume all of the newly installed packages are on the system path. I was hoping there is a way that I can import the new modules without restarting the script though.
I tried reload(sys) but it didn't help me. I can hack it by manually appending to sys.path or by starting a new python script using os.system(), but I would prefer a cleaner solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可能有更清洁的解决方案。您正在安装一个软件包,这会导致系统路径更新。您必须修改路径或启动一个在新环境中工作的子脚本。
还。不要使用
os.system
。请使用子进程
。执行此操作风险最小的方法是拥有一个仅执行两种操作的“主”脚本。
使用
subprocess.Popen
运行easy_install 脚本序列。使用
subprocess.Popen
在所有 easy_install 脚本之后完成其余工作。由于这是一个单独的进程,因此它可以构建一个单独的 Python PATH,其中包含所有新包。There cannot be a cleaner solution. You're installing a package, which leads to an update to the system path. You must either tinker with the path or start a sub-script that works in a new environment.
Also. Don't use
os.system
. Please usesubprocess
.The least risky way to do this is to have a "master" script which only does two kinds of things.
Use
subprocess.Popen
to run the sequence of easy_install scripts.Use
subprocess.Popen
to do the rest of the work after all the easy_install scripts. Since this is a separate process, it can build a separate Python PATH with all of the new packages in it.看看Fabric,看看它会做出什么东西你的生活变得轻松多了。
Django 集成 这里。
Have a look at Fabric, by the looks of things it'll make your life a lot easier.
Django integration here.
您需要重新加载
site
模块,而不是sys
:"导入此模块会将特定于站点的路径附加到模块搜索路径并添加一些内置函数。 "
另外,考虑使用
importlib.import_module
而不是__import__
:这是一个高级函数,日常 Python 编程中不需要,与 importlib.import_module( )。
You need to reload
site
module, notsys
:"Importing this module will append site-specific paths to the module search path and add a few builtins."
Also, consider using of
importlib.import_module
instead of__import__
:This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().