【问题标题】:Calling a function from another python script with a while loop使用while循环从另一个python脚本调用函数
【发布时间】:2016-08-22 07:18:01
【问题描述】:

我有一个带有一个函数和一个 while 循环的 python 脚本,我想从另一个也有一个 while 循环的 python 脚本调用这个函数。这是一个示例脚本:

script1.py:

global printline
printline = abc

def change(x):
    global printline
    printline = x

while True:
    global printline
    print printline

这是script2.py:

from script1 import change

change(xyz)

while True:
    print hello

当我运行 script2.py 时,它开始打印 abc 并且不会进入此脚本中的 while 循环。

当我运行 script1.py 时,它会打印 abc。

当我在不同的终端同时运行两者时,都打印 abc。

我需要它,以便当两个脚本都运行时,script2.py 可以在进入 while 循环时更改变量 printline。

我不知道这是否是正确的方法,因为我是 python 新手。

谢谢。

【问题讨论】:

  • 那些不可能是您的实际脚本。在abcxyz 上不会出现“名称未定义”错误吗?请逐字发布您遇到问题的实际代码,否则任何人都只能猜测。
  • 这些脚本是否应该是共享相同printline 变量的独立程序?例如,当两个脚本同时运行时,它们共享相同的printline 变量?
  • abcxyz 是否应该是字符串 "abc""xyz"
  • global 语句放在函数之外是没有意义的。
  • 当你从文件中导入时,所有不在函数中的语句都会正常执行,就像你自己运行脚本一样。所以script1.py 中的while True: 代码执行,它永远不会退出那个无限循环。模块文件中的顶级语句只是用于初始化模块,它们需要完成。

标签: python


【解决方案1】:

当您执行from script1 import change 时,它会执行script1.py 中的所有顶级代码。因此它会执行while True: 块,该块无限循环,并且永远不会返回到script2.py

需要拆分script1.py,这样就可以在不执行顶层代码的情况下导入change()函数。

更改.py:

def change(x):
    global printline
    printline = x

script1.py:

from change import change

change("abc")
while True:
    print printline

script2.py:

from change import change

change("xyz");
while True:
    print printline

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多