首页 > 解决方案 > 如何在同一目录中导入其他脚本?

问题描述

我正在尝试将一些 python 脚本安排在main.py. 这些脚本放在同一个文件夹中。

main.py

import schedule
import time
from test1 import dd

schedule.every(2).seconds.do(dd,fname)

while True:
    schedule.run_pending()
    time.sleep(1)

test1.py

def dd(fname):
    print('hello' + fname)

dd('Mary')
dd('John')

它以那 2 个名称和 name 'fname' is not defined.

如何在main.py文件中定义参数?如果我在脚本中有多个,我是否需要在 我导入的脚本中def多次导入,它在运行计划之前运行一次?这意味着它会在您导入时运行一个?main.pymain.py

标签: pythonschedule

解决方案


您没有在 main.py 中定义您的 fname,所以它说name 'fname' is not defined。您只是将函数从 test1.py 导入到 main.py

这是修改后的代码:
main.py

import schedule
import time
from test1 import dd

fname="Mary"
schedule.every(2).seconds.do(dd,fname)

while True:
    schedule.run_pending()
    time.sleep(1)

测试1.py

def dd(fname):
    print('hello' + fname)

如果您想输入多个字符串,只需使用一个列表!下面是 test1.py 的示例代码:

def dd(fname:list):
    for n in fname:
        print('hello' + n)

这些代码使用 Python 3.7.7 进行测试


推荐阅读