【问题标题】:How to import other script in same dir?如何在同一目录中导入其他脚本?
【发布时间】:2020-08-05 15:30:44
【问题描述】:

我正在尝试将一些 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')

这两个名字和name 'fname' is not defined 用完了。

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

【问题讨论】:

  • fname 是运行时函数范围内唯一定义的。使用dd("Mary")或变量调用函数,然后在函数内部fname将被定义为你传入的任何内容。

标签: python schedule


【解决方案1】:

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

这是修改后的代码:
ma​​in.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 测试

【讨论】:

  • 感谢您的帮助,它有效。那么fname 是一个像循环名称一样的 forloop 函数呢
  • 那么在这种情况下,我认为您可以将 fname 从字符串更改为列表并在您的 dd 函数中对其进行迭代
【解决方案2】:

您的问题是您试图将函数参数用作它自己的变量。导入不是这里的问题。

试试这个:

import schedule
import time
from test1 import dd

schedule.every(2).seconds.do(dd,("Any String",))

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 2012-05-03
    • 1970-01-01
    • 2022-01-21
    • 2021-09-14
    • 2011-05-07
    相关资源
    最近更新 更多