是否可以从函数(Python)中导入全局范围? [英] Is it possible to import to the global scope from inside a function (Python)?

查看:117
本文介绍了是否可以从函数(Python)中导入全局范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从函数内部导入一个模块,并使其可用于我的整个文件,就像我在任何函数之外和所有其他代码之前导入一样。它在函数中的原因是因为我对脚本的结构没有太多控制权。这是不是可以在不使用hacking __builtin__或者在我的代码周围传递我需要的东西?

I am trying to import a module from inside a function and have it be available to my whole file the same way it would be if I imported outside any functions and before all the other code. The reason it is in a function is because I don't have much control over the structure of the script. Is this possible without resorting to things like hacking __builtin__ or passing what I need all around my code?

推荐答案

如何像 globals()[os] = __import __(os)?

我想这可能包含在因为模块名称是一个字符串,所以你需要一个通用函数。

I guess this could be wrapped in a generic function if you wanted since the module name is a string.

这篇关于是否可以从函数(Python)中导入全局范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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