如何将其分成两个文件?
How do I separate this into two files?
这完全有效,但当它们位于单独的文件中时则无效,如下所示:
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 = '3[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
如果我理解正确的话,我会这样做:
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 = '3[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 a test
用蓝色慢慢写。
这完全有效,但当它们位于单独的文件中时则无效,如下所示: 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 = '3[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
如果我理解正确的话,我会这样做:
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 = '3[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 a test
用蓝色慢慢写。