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

查看:60
本文介绍了为什么导入时 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 运行我正在导入的main"模块中包含的代码?

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.

惯用的方法是:

# 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__" for?

不过,它确实需要对正在导入的模块进行源代码控制.

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

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

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