如何在同一目录中导入其他脚本?
How to import other script in same dir?
我正在尝试将一些 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.py
中多次导入
以及我在 main.py
顶部导入的脚本,它会在 运行 计划之前 运行 一次?这意味着它会 运行 一个而你导入它?
您没有在 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)
test1.py
def dd(fname):
print('hello' + fname)
如果要输入多个字符串,直接使用列表即可!这是 test1.py:
的示例代码
def dd(fname:list):
for n in fname:
print('hello' + n)
这些代码使用 Python 3.7.7
进行测试
您的问题是您试图将函数参数用作它自己的变量。导入不是这里的问题。
试试这个:
import schedule
import time
from test1 import dd
schedule.every(2).seconds.do(dd,("Any String",))
while True:
schedule.run_pending()
time.sleep(1)
我正在尝试将一些 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.py
中多次导入
以及我在 main.py
顶部导入的脚本,它会在 运行 计划之前 运行 一次?这意味着它会 运行 一个而你导入它?
您没有在 main.py 中定义您的 fname,因此显示 name 'fname' is not defined
。您只是将函数从 test1.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)
test1.py
def dd(fname):
print('hello' + fname)
如果要输入多个字符串,直接使用列表即可!这是 test1.py:
的示例代码def dd(fname:list):
for n in fname:
print('hello' + n)
这些代码使用 Python 3.7.7
进行测试您的问题是您试图将函数参数用作它自己的变量。导入不是这里的问题。
试试这个:
import schedule
import time
from test1 import dd
schedule.every(2).seconds.do(dd,("Any String",))
while True:
schedule.run_pending()
time.sleep(1)