Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何在不执行其他代码的情况下导入对象?_Python_Module - Fatal编程技术网

在Python中,如何在不执行其他代码的情况下导入对象?

在Python中,如何在不执行其他代码的情况下导入对象?,python,module,Python,Module,例如,以a.py为例 stringcheese = "hi" print("I don't want this printed") 现在b.py: from a import stringcheese print(stringcheese) 输出为: I don't want this printed hi 我怎样才能导入stringcheese而不执行a.py的代码?你不能。必须首先执行模块的顶级代码,才能加载模块 只将可执行语句放在模块的顶层,这样您就可以在导入时执行了。POSUM S

例如,以a.py为例

stringcheese = "hi"
print("I don't want this printed")
现在b.py:

from a import stringcheese
print(stringcheese)
输出为:

I don't want this printed
hi

我怎样才能导入
stringcheese
而不执行
a.py
的代码?

你不能。必须首先执行模块的顶级代码,才能加载模块


只将可执行语句放在模块的顶层,这样您就可以在导入时执行了。

POSUM SHREDER,如果uuu name uuuu='\uuuu main uuu'构造来隐藏未插入的可执行文件,那么调用
python a.py
仍将执行它们

a、 派克

main.py

from a import stringcheese
print(stringcheese)

有关更多详细信息,请阅读

您的答案是正确的,但请稍微解释一下您的答案。不要只转储代码,这样其他人和OP就可以learn@Trigremm你的答案仍然可以使用更多的爱,比如快速解释链接之外的
\uu name\uu
。不过,我对你的编辑工作表示感谢,这比你最初的版本有了很大的改进。欢迎使用堆栈溢出。对不起,顶层是什么意思?@POSUMSHREDER:函数之外的任何模块代码(函数对象已创建,但它们的代码在调用函数之前不会执行)。
from a import stringcheese
print(stringcheese)