只想导入一个函数,但完整的程序来了

2024-06-28 19:10:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了两个节目。我想将全局变量从transmitter函数导入到另一个文件中,但是我遇到的问题是While true循环也会破坏我的整个第二个程序,因为第二个问题现在也开始显示它

方案1:

import time

def transmitter():
    global temp

global temp
temp = 2

transmitter()

while True: # a random task just to see if I only imported the function
    x = 0
    print(x + 1)
    time.sleep(0.2)

方案2:

from transmitguy import transmitter

def valuepullup():
    newval = transmitguy.transmitter()
    print(newval)

valuepullup()

我只需要我的第二个程序显示一次2的值(2是文件1中的globalvar)


Tags: 文件import程序timedef方案global节目
1条回答
网友
1楼 · 发布于 2024-06-28 19:10:49

简而言之,你不可能只得到一个模块的一部分from x import yimport x相同的方式导入x。唯一的区别是,在前一种情况下,y被添加到当前全局名称空间,在后一种情况下,x被添加到当前全局名称空间。这个docs for ^{}说:

The from form ... find[s] the module specified in the from clause, loading and initializing it if necessary ...

我不确定你到底想做什么。正如评论者所指出的,您可以检查__main__。但是,最好将变量放在自己的模块中,然后从两个现有模块导入该模块

另见the tutorial

相关问题 更多 >