【问题标题】:Does a .py get executed when being imported [python3]导入时是否执行 .py [python3]
【发布时间】:2014-09-21 13:26:13
【问题描述】:

我需要执行一个文件,所以我想知道它是否像这样工作?需要执行的文件会创建一个数据库。

【问题讨论】:

  • 是吗?如果代码正确?你能更详细地描述你的问题吗?
  • @Timo 没有真正的问题,我只想知道如果我导入它是否会执行,我猜你给了我答案,谢谢!

标签: python sql python-3.x sqlalchemy python-import


【解决方案1】:

好的,我也在这里草拟了答案。如果代码没有封装在类或函数中,它将运行。例如:

def f():
    print ('This line will not be executed during import from another file')

print ('This line is executed!')

if __name__ == '__main__':
    print ('This line is executed only, if the program is main program, but not during import from another program.')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2021-08-01
    • 1970-01-01
    • 2021-07-26
    • 2017-05-17
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多