【问题标题】:Python: How to block user from calling module via another module(by attributing it)?Python:如何阻止用户通过另一个模块调用模块(通过归因)?
【发布时间】:2021-06-24 20:09:45
【问题描述】:

我的模块中有一个 python 库os。但是,我不希望用户调用os,例如:my_module.os。我需要对exec() 进行此限制,以允许用户仅使用指定的模块。也许可以用AST 完成。 如何正确检查代码以发现类似情况?还是不可能?

【问题讨论】:

    标签: python python-3.x exec python-3.9


    【解决方案1】:

    你可以把my_module做成一个python包,结构如下。

    my_module/
    |-- __init__.py
    |-- my_module.py
    

    例如my_module.py 具有以下结构。

    import os
    
    def function_one():
    .
    .
    .
    
    
    def function_two():
    .
    .
    .
    

    现在在__init__.py里面

    from my_module import function_one, function_two
    

    现在,当您在 example.py 中导入 my_module 时,您将只能使用 function_onefunction_two

    example.py 文件:

    import my_module
    
    my_module.function_one()    #runs without issues
    
    my_module.os    #throws attribute error
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多