怎么if __name__ == "__main__":办?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
Run Code Online (Sandbox Code Playgroud) 这个问题不是讨论单身人士设计模式是否可取,反模式,还是任何宗教战争,而是讨论如何以最蟒蛇的方式在Python中最好地实现这种模式.在这种情况下,我将"最pythonic"定义为表示它遵循"最小惊讶原则".
我有多个类可以成为单例(我的用例是记录器,但这并不重要).当我可以简单地继承或装饰时,我不希望在添加gumph的几个类中混乱.
最好的方法:
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass(BaseClass):
pass
Run Code Online (Sandbox Code Playgroud)
优点
缺点
m = MyClass(); n = MyClass(); o = type(n)();那时m == n && m != o && n != oclass Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class MyClass(Singleton, …Run Code Online (Sandbox Code Playgroud) 我希望通过我希望处理日志的方式来处理所有警告.甚至在导入库期间发出的这些.
这意味着必须在导入库之前完成日志记录的配置.
搜索一段时间之后,我认为在自定义中配置日志记录sitecustomize.py可能是一种解决方案
但sitecustomize.py不知何故,黑魔法只有少数人知道它,甚至更少的人使用它.
有没有更明显的方法来确保在导入库之前完成我的日志配置?
不幸的是,似乎无法通过环境变量配置日志记录.
更新
根据我的观点,我没有得到任何可以接受的答案.我认为你需要将登录分为两个责任区:
一旦第一行代码被python解释器执行,区域"环境"就对代码负责.现在做任何配置都为时已晚.我想看看将日志记录设置为调用python解释器的一部分.
一种解决方案可以是环境变量:
PYTHON_LOGGING_CONFIG=/path-to-env/etc/config.yaml
Run Code Online (Sandbox Code Playgroud)
或者是翻译的参数:
python --logging-config=path-to-env/etc/config.yaml script.py
Run Code Online (Sandbox Code Playgroud) python ×3
base-class ×1
decorator ×1
idioms ×1
logging ×1
metaclass ×1
namespaces ×1
singleton ×1