[英]Import into python interpreter main namespace from an import
How can I run a bunch of imports and path appends from the interpreter with one command/import? 如何使用一个命令/导入从解释器运行一堆导入和路径追加? If I import another module that runs the commands for me the imports are not available in main namespace. 如果导入另一个为我运行命令的模块,则导入在主名称空间中不可用。 Similar to running a bash script that modifies/adds commands and variables to the current session. 与运行bash脚本类似,该脚本可在当前会话中修改/添加命令和变量。
ex. 恩。
import os, ...
sys.path.append(...)
If I understand you correctly, you're just looking for the from … import …
statement. 如果我理解正确,那么您只是在寻找from … import …
语句。 For example: 例如:
lotsostuff.py: lotsostuff.py:
import json
def foo(): pass
Now: 现在:
$ python3.3
>>> from lotsostuff import *
>>> json
<module 'json' from '/usr/local/lib/python3.3/json/__init__.py'>
>>> foo
<function lotsostuff.foo>
However, you might want to consider a different alternative. 但是,您可能需要考虑其他选择。 If you're just trying to control the startup of your interpreter session, you can do this: 如果您只是想控制解释器会话的启动,则可以执行以下操作:
$ PYTHONSTARTUP=lotsostuff.py
$ python3.3
>>> json
<module 'json' from '/usr/local/lib/python3.3/json/__init__.py'>
>>> foo
<function __main__.foo>
Notice the difference in the last line. 注意最后一行的不同。 You're now running lotsostuff
in the __main__
namespace, rather than running in a separate namespace and grabbing all of its members. 您现在在__main__
命名空间中运行lotsostuff
,而不是在单独的命名空间中运行并获取其所有成员。
Similarly: 同理:
$ python3.3 -i lotsostuff.py
>>> json
<module 'json' from '/usr/local/lib/python3.3/json/__init__.py'>
You'd normally use PYTHONSTARTUP
if you want to do this every time in your session, -i
if you want to do it just this once. 如果您每次在会话中都想这样做,通常会使用PYTHONSTARTUP
如果只想一次,则使用-i
。
If you want to do the same thing in the middle of a session instead of at startup… well, you can't do it directly, but you can come pretty close with exec
(Python 3.x) (or execfile
in Python 2.x). 如果您想在会话中间而不是在启动时做同样的事情……好吧,您不能直接这样做,但是您可以非常接近exec
(Python 3.x)(或Python 2中的execfile
)。 X)。
If you really want to do exactly what you described—importing a module, as a normal import, except merged into your namespace instead of in its own—you'll need to customize the import process. 如果您确实想按照自己的描述进行操作(作为模块的常规导入方式导入模块,除了合并到您的命名空间中而不是单独合并),则需要自定义导入过程。 This isn't that hard with importlib
; 使用importlib
并不难; if you're not in Python 3.2 or later, you'll have a lot more work to do it with imp
. 如果您不是使用Python 3.2或更高版本,则需要使用imp
更多工作。
That's pretty much the difference between . ./foo
两者之间的差别差不多. ./foo
. ./foo
instead of just ./foo
in a bash
script that I think you were looking for. . ./foo
而不是我认为您正在寻找的bash
脚本中的./foo
。
If you're using ipython
, there are even cooler options. 如果您使用的是ipython
,则还有更酷的选择。 (And if you're not using ipython
, you might want to check it out.) (如果您不使用ipython
,则可能需要检查一下。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.