为什么在导入模块时Python运行我的模块,以及如何停止它? [英] Why is Python running my module when I import it, and how do I stop it?

查看:125
本文介绍了为什么在导入模块时Python运行我的模块,以及如何停止它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Python程序,该程序可以通过以下两种方式之一运行:第一种是调用"python main.py",它以友好的方式提示用户输入,然后通过以下方式运行用户输入该程序.另一种方法是调用"python batch.py​​ -file-",它将遍历所有友好的输入集合,并通过该程序一次运行整个文件的输入值.

I have a Python program I'm building that can be run in either of 2 ways: the first is to call "python main.py" which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call "python batch.py -file-" which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.

问题是,当我运行"batch.py​​"时,它会从"main.py"中导入一些变量/方法/等,并在运行此代码时:

The problem is that when I run "batch.py" it imports some variables/methods/etc from "main.py", and when it runs this code:

import main

在程序的第一行,它立即错误,因为它试图运行"main.py"中的代码.

at the first line of the program, it immediately errors because it tries to run the code in "main.py".

如何阻止Python运行要导入的主"模块中包含的代码?

How can I stop Python from running the code contained in the "main" module which I'm importing?

推荐答案

因为这就是Python的工作方式-classdef之类的关键字不是声明.相反,它们是被执行的真实实时语句.如果未执行,则您的模块将为..空:-)

Because this is just how Python works - keywords such as class and def are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be .. empty :-)

无论如何,惯用的方法是:

Anyway, the idiomatic approach is:

# stuff to run always here such as class/def
def main():
    pass

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

请参见 if __name__ == "__main__"的作用是什么?

See What is if __name__ == "__main__" for?

但是,它确实需要对要import的模块进行源代码控制.

It does require source control over the module being imported, however.

快乐的编码.

这篇关于为什么在导入模块时Python运行我的模块,以及如何停止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆