为什么Python在导入时会运行我的模块,如何阻止它?

时间:2022-03-08 20:19:56

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.

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

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

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

import main

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

在程序的第一行,它立即出错,因为它试图在“main.py”中运行代码。

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

如何阻止Python运行我正在导入的“main”模块中包含的代码?

9 个解决方案

#1


158  

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 :-)

因为这就是Python的工作原理 - 类和def等关键字不是声明。相反,它们是真实的实时语句。如果他们没有执行你的模块将是..空:-)

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()

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

请参阅什么是__name__ ==“__ main__”?

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

但是,它确实需要对正在导入的模块进行源代码控制。

Happy coding.

快乐的编码。

#2


29  

Due to the way Python works, it is necessary for it to run your modules when it imports them.

由于Python的工作方式,它必须在导入模块时运行它们。

To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this if:

为了防止模块中的代码在导入时执行,但仅在直接运行时,您可以使用以下命令对其进行保护:

if __name__ == "__main__":
    # this won't be run when imported

You may want to put this code in a main() method, so that you can either execute the file directly, or import the module and call the main(). For example, assume this is in the file foo.py.

您可能希望将此代码放在main()方法中,以便您可以直接执行文件,也可以导入模块并调用main()。例如,假设它位于文件foo.py中。

def main():
    print "Hello World"

if __name__ == "__main__":
    main()

This program can be run either by going python foo.py, or from another Python script:

这个程序可以通过运行python foo.py或从另一个Python脚本运行:

import foo

...

foo.main()

#3


6  

Use the if __name__ == '__main__' idiom -- __name__ is a special variable whose value is '__main__' if the module is being run as a script, and the module name if it's imported. So you'd do something like

使用if __name__ =='__ main__'idiom - __name__是一个特殊变量,如果模块作为脚本运行,则其值为“__main__”,如果导入模块名称则为模块名称。所以你会做类似的事情

# imports
# class/function definitions
if __name__ == '__main__':
    # code here will only run when you invoke 'python main.py'

#4


4  

Unfortunately, you don't. That is part of how the import syntax works and it is important that it does so -- remember def is actually something executed, if Python did not execute the import, you'd be, well, stuck without functions.

不幸的是,你没有。这是导入语法如何工作的一部分,重要的是它这样做 - 记住def实际上是执行的东西,如果Python没有执行导入,那么你就会没有功能。

Since you probably have access to the file, though, you might be able to look and see what causes the error. It might be possible to modify your environment to prevent the error from happening.

但是,由于您可能有权访问该文件,因此您可以查看并查看导致错误的原因。可以修改您的环境以防止错误发生。

#5


3  

put the code inside a function and it won't run until you call the function. You should have a main function in your main.py. with the statement:

把代码放在一个函数中,直到你调用函数它才会运行。你应该在main.py中有一个main函数。声明:

if __name__ == '__main__': main()

then, if you call "python main.py" the main() function will run. If you import main.py, it will not. Also, you should probably rename main.py to something else for clarity sake.

然后,如果你调用“python main.py”,main()函数将运行。如果导入main.py,则不会。此外,为了清楚起见,您可能应该将main.py重命名为其他内容。

#6


2  

You may write your "main.py" like this:

您可以像这样写下“main.py”:

#!/usr/bin/env python

__all__=["somevar", "do_something"]

somevar=""

def do_something():
    pass #blahblah

if __name__=="__main__":
    do_something()

#7


0  

Although you cannot use import without running the code; there is quite a swift way in which you can input your variables; by using numpy.savez, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using numpy.load.

虽然在不运行代码的情况下无法使用导入;你可以通过一种快速的方式输入你的变量;通过使用numpy.savez,它将变量存储为.npz文件中的numpy数组。之后,您可以使用numpy.load加载变量。

See a full description in the scipy documentation

请参阅scipy文档中的完整说明

Please note this is only the case for variables and arrays of variable, and not for methods, etc.

请注意,这仅适用于变量和变量数组,而不适用于方法等。

#8


-1  

There was a Python enhancement proposal PEP 299 which aimed to replace if __name__ == '__main__': idiom with def __main__:, but it was rejected. It's still a good read to know what to keep in mind when using if __name__ = '__main__':.

有一个Python增强提议PEP 299旨在用def __main__:替换if __name__ =='__ main__':idiom,但它被拒绝了。在使用if __name__ ='__ main__'时,了解要记住的内容仍然是一个很好的读物:

#9


-3  

Try just importing the functions needed from main.py? So,

尝试从main.py导入所需的功能?所以,

from main import SomeFunction

It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.

可能是你在batch.py​​中命名了一个与main.py中的函数相同的函数,当你导入main.py时,程序运行main.py函数而不是batch.py​​函数;做上述事情应该解决这个问题。我希望。

#1


158  

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 :-)

因为这就是Python的工作原理 - 类和def等关键字不是声明。相反,它们是真实的实时语句。如果他们没有执行你的模块将是..空:-)

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()

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

请参阅什么是__name__ ==“__ main__”?

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

但是,它确实需要对正在导入的模块进行源代码控制。

Happy coding.

快乐的编码。

#2


29  

Due to the way Python works, it is necessary for it to run your modules when it imports them.

由于Python的工作方式,它必须在导入模块时运行它们。

To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this if:

为了防止模块中的代码在导入时执行,但仅在直接运行时,您可以使用以下命令对其进行保护:

if __name__ == "__main__":
    # this won't be run when imported

You may want to put this code in a main() method, so that you can either execute the file directly, or import the module and call the main(). For example, assume this is in the file foo.py.

您可能希望将此代码放在main()方法中,以便您可以直接执行文件,也可以导入模块并调用main()。例如,假设它位于文件foo.py中。

def main():
    print "Hello World"

if __name__ == "__main__":
    main()

This program can be run either by going python foo.py, or from another Python script:

这个程序可以通过运行python foo.py或从另一个Python脚本运行:

import foo

...

foo.main()

#3


6  

Use the if __name__ == '__main__' idiom -- __name__ is a special variable whose value is '__main__' if the module is being run as a script, and the module name if it's imported. So you'd do something like

使用if __name__ =='__ main__'idiom - __name__是一个特殊变量,如果模块作为脚本运行,则其值为“__main__”,如果导入模块名称则为模块名称。所以你会做类似的事情

# imports
# class/function definitions
if __name__ == '__main__':
    # code here will only run when you invoke 'python main.py'

#4


4  

Unfortunately, you don't. That is part of how the import syntax works and it is important that it does so -- remember def is actually something executed, if Python did not execute the import, you'd be, well, stuck without functions.

不幸的是,你没有。这是导入语法如何工作的一部分,重要的是它这样做 - 记住def实际上是执行的东西,如果Python没有执行导入,那么你就会没有功能。

Since you probably have access to the file, though, you might be able to look and see what causes the error. It might be possible to modify your environment to prevent the error from happening.

但是,由于您可能有权访问该文件,因此您可以查看并查看导致错误的原因。可以修改您的环境以防止错误发生。

#5


3  

put the code inside a function and it won't run until you call the function. You should have a main function in your main.py. with the statement:

把代码放在一个函数中,直到你调用函数它才会运行。你应该在main.py中有一个main函数。声明:

if __name__ == '__main__': main()

then, if you call "python main.py" the main() function will run. If you import main.py, it will not. Also, you should probably rename main.py to something else for clarity sake.

然后,如果你调用“python main.py”,main()函数将运行。如果导入main.py,则不会。此外,为了清楚起见,您可能应该将main.py重命名为其他内容。

#6


2  

You may write your "main.py" like this:

您可以像这样写下“main.py”:

#!/usr/bin/env python

__all__=["somevar", "do_something"]

somevar=""

def do_something():
    pass #blahblah

if __name__=="__main__":
    do_something()

#7


0  

Although you cannot use import without running the code; there is quite a swift way in which you can input your variables; by using numpy.savez, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using numpy.load.

虽然在不运行代码的情况下无法使用导入;你可以通过一种快速的方式输入你的变量;通过使用numpy.savez,它将变量存储为.npz文件中的numpy数组。之后,您可以使用numpy.load加载变量。

See a full description in the scipy documentation

请参阅scipy文档中的完整说明

Please note this is only the case for variables and arrays of variable, and not for methods, etc.

请注意,这仅适用于变量和变量数组,而不适用于方法等。

#8


-1  

There was a Python enhancement proposal PEP 299 which aimed to replace if __name__ == '__main__': idiom with def __main__:, but it was rejected. It's still a good read to know what to keep in mind when using if __name__ = '__main__':.

有一个Python增强提议PEP 299旨在用def __main__:替换if __name__ =='__ main__':idiom,但它被拒绝了。在使用if __name__ ='__ main__'时,了解要记住的内容仍然是一个很好的读物:

#9


-3  

Try just importing the functions needed from main.py? So,

尝试从main.py导入所需的功能?所以,

from main import SomeFunction

It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.

可能是你在batch.py​​中命名了一个与main.py中的函数相同的函数,当你导入main.py时,程序运行main.py函数而不是batch.py​​函数;做上述事情应该解决这个问题。我希望。