简体   繁体   English

我应该如何更改“__main__”str 以运行具有 if __name__==“__main__”的文件:

[英]how should I change "__main__" str to run file that has if __name__=="__main__":

I have many python files and sometimes I need to check them if they works.我有很多 python 文件,有时我需要检查它们是否有效。 So they require different import ways in the file for libraries.因此,它们在库文件中需要不同的导入方式。 The below code explains the situation.下面的代码解释了这种情况。

I use else situations for fles that import XLS .我对导入XLS的文件使用else情况。

XLS.py

if __name__ == "__main__":
    import config
else:
    import DataLoaders.config as config


However I want to add dataset.py file to if situation.但是我想在if情况下添加dataset.py文件。

if __name__ == "__main__" or __name__=="dataset.py":
    import config
else:
    import DataLoaders.config as config

I tried above code but it doesn't work.我试过上面的代码,但它不起作用。 How to add the file name in if to import config file as demanded?如何在if中添加文件名按需导入配置文件?

__file__ return the path of the python file that is currently running. __file__返回当前运行的 python 文件的路径。 You can use the fonction os.path.basename() to extract only the name of the file.您可以使用函数os.path.basename()仅提取文件名。

Here is an example:这是一个例子:

import os

filename = os.path.basename(__file__)
print(filename)

It returns:它返回:

>>> test.py

You can then use a condition to check the name of the file and import the desired modules.然后您可以使用条件来检查文件的名称并导入所需的模块。

__name__ is set to the name of the module , not whatever creates the module. __name__设置为模块的名称,而不是创建模块的名称。 So in XLS.py , its value is either "__main__" , if the file is executed as a script, or XLS , if the module is imported by someone else.因此,在XLS.py中,如果文件作为脚本执行,则其值为"__main__" ;如果模块是由其他人导入的,则为XLS

The problem here is that config is, to some extent, a parameter for your module, whose value is determined elsewhere.这里的问题是config在某种程度上是模块的参数,其值在其他地方确定。 ( config , if you execute as a script, Databases.config if you import from dataset.py , maybe some other module if you import from elsewhere.) config ,如果您作为脚本执行, Databases.config如果您从dataset.py导入,如果您从其他地方导入,则可能是其他模块。)

Python, unfortunately, doesn't allow you to parameterize an import like you can a function.不幸的是,Python 不允许您像函数一样参数化导入。 A workaround is to simply leave config undefined in XLS.py , and leave the caller the responsibility to set the value appropriately.一种解决方法是简单地在XLS.py中保留未定义config ,并让调用者负责适当地设置值。

# XLS.py
...

if __name__ == "__main__":
   import config
   ...

# dataset.py
import XLS
import DataLoaders

XLS.config = DataLoaders.config
...

This works as long as XLS doesn't use config at import time;只要XLS在导入时不使用config ,这就有效; I assume it's just a name that other functions in the module may refer to when they are called .我假设它只是模块中其他函数在调用时可能引用的名称。

Frequently this is better accomplished by either (though logically these end up the same because they both split import logic off)通常这两者都可以更好地完成(尽管逻辑上它们最终是相同的,因为它们都将导入逻辑分开了)

  • splitting off functionality into separate files and importing it where needed将功能拆分为单独的文件并在需要的地方导入
  • keeping all of the relevant logic together in a custom class or method of one将所有相关逻辑放在一个自定义类或方法中

An example of this using @classmethod (which largely exists to aid this sort of design) could be一个使用@classmethod的例子(它的存在主要是为了帮助这种设计)可能是

class MyClass:

    @classmethod
    def from_XLS(cls, xls_path):
        import custom_xls_loader
        data = custom_xls_loader.load(xls_path)
        # call any other other needed transform methods
        # opportunity to make result an instance of this class
        #   (otherwise why not use a normal function)
        return cls(data)

This is used for optional support in many large libraries (where there may be a huge number of busy dependencies that a user may not want or need to install for their use case)这用于许多大型库中的可选支持(其中可能有大量繁忙的依赖项,用户可能不希望或不需要为他们的用例安装)
Here's an example from Pandas where some Apache Arrow support is optional https://github.com/pandas-dev/pandas/blob/bbb1cdf13a1e9240b43d691aa0ec3ca1b37afee4/pandas/core/arrays/arrow/dtype.py#L112这是 Pandas 的一个示例,其中一些 Apache Arrow 支持是可选的https://github.com/pandas-dev/pandas/blob/bbb1cdf13a1e9240b43d691aa0ec3ca1b37afee4/pandas/core/arrays/arrow/dtype.py#L112


Or in your case (referring to config as self.config in the class or as the .config property of an instance)或者在您的情况下(将配置称为类中的self.config或实例的.config属性)

class MyClass

    def __init__(self, data, config=None)
        if config is None:
            import config
        self.config = config

    @classmethod
    def from_config_normal(cls, data):
        return cls(data)

    @classmethod
    def from_DataLoaders_config(cls, data):
        import DataLoaders.config as config
        return cls(data, config)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM