如何将其分成两个文件?

发布于 2025-01-09 01:29:17 字数 731 浏览 0 评论 0原文

这完全有效,但是当它们位于单独的文件中时则不起作用,如下所示: main.py

from write import *

def write():
    global text
    text = "this is a test"
    colour()

write()

color.py

import sys
from time import sleep

blue = '\033[0;34m'

def colour():
    for char in text:
        sleep(0.05)
        sys.stdout.write(blue)
        sys.stdout.write(char)
        sys.stdout.flush()
    sleep(0.5)

错误如下:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    write()
  File "main.py", line 6, in write
    colour()
  File "/home/runner/Function-Test/colour.py", line 7, in colour
    for char in text:
NameError: name 'text' is not defined

This works altogether, however doesn't when they are inside separate files, like so:
main.py

from write import *

def write():
    global text
    text = "this is a test"
    colour()

write()

colour.py

import sys
from time import sleep

blue = '\033[0;34m'

def colour():
    for char in text:
        sleep(0.05)
        sys.stdout.write(blue)
        sys.stdout.write(char)
        sys.stdout.flush()
    sleep(0.5)

Error is as follows:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    write()
  File "main.py", line 6, in write
    colour()
  File "/home/runner/Function-Test/colour.py", line 7, in colour
    for char in text:
NameError: name 'text' is not defined

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟─花易冷 2025-01-16 01:29:17

如果我理解正确的话,我会这样做:

write.py

from colour import colour

def write():
    text = "this is a test"
    colour(text)

write()

color.py

import sys
from time import sleep

blue = '\033[0;34m'

def colour(text):
    for char in text:
        sleep(0.05)
        sys.stdout.write(blue)
        sys.stdout.write(char)
        sys.stdout.flush()
    sleep(0.5)

结果:

这是一个测试 用蓝色慢慢写。

This is how I would do it if I understand correctly:

write.py

from colour import colour

def write():
    text = "this is a test"
    colour(text)

write()

colour.py

import sys
from time import sleep

blue = '\033[0;34m'

def colour(text):
    for char in text:
        sleep(0.05)
        sys.stdout.write(blue)
        sys.stdout.write(char)
        sys.stdout.flush()
    sleep(0.5)

Result:

this is a test Written slowly in Blue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文