0

例子:

测试.py

class test_class(object):
    def display(self):
        print "Hello"

锁1.py

from test import test_class
from time import sleep
obj = test_class()
while True:
    obj.display()
    sleep(1)

锁2.py

from test import test_class
obj = test_class()
# Raise error if instance of test_class has been implemented before
try:
   obj.display()
except Exception as e:
   print e

我需要做的是锁定(或任何东西)文件lock2.py的类(或整个test.py),如果在引发错误(或Expeption)之前已经为该类初始化了对象。尽管该示例可能看起来不相关,但我已经简化了该示例。

我尝试使用锁定文件即 test.py

http://packages.python.org/lockfile/lockfile.html

http://pypi.python.org/pypi/zc.lockfile

但这似乎没有帮助。


这是一个实际的代码片段

comm_port.py

import serial
class CommPort(object):
    def __init__(self):
        self.ser = serial.Serial("/dev/ttyUSB0")
        # update in db (I've removed actual db update process
        # db.flag = 1        

访问文件1.py

from comm_port import CommPort
# if db.flag != 1:
    port = Commport()
    port.ser.flushInput()
    port.ser.flushOutput()
    ## will flush the buffer.. what if it flused the data that was supposed for go for accessing_file2
    port.ser.write("1")
    # do stuff using serial-port object "port"
    # lets say script gets busy for 30 secs for doing some stuffs
    # db.flag = 0

访问文件2.py

from comm_port import CommPort
# if db.flag != 1:
    port = Commport()
    port.ser.flushInput()
    port.ser.flushOutput()
    port.ser.write("2")
    # do stuff using serial-port object "port"
    # lets say script gets busy for 40 secs for doing some stuffs
    # db.flag = 0

这个例子可能看起来并不相关,但这是我的情况。两个文件也可以同时激活,但我一次只需要一个文件来操作。如果使用 comm_port.py 并且其余文件检查此标志,我所做的是创建一个 db 标志。如果 comm_port 忙,其他访问文件将无法工作。但我不认为它的最佳做法。

所以我需要检查是否有办法检查 CommPort 类是否被任何对象或锁定 comm_port.py 或任何其他现有的想法是最受欢迎的。

4

2 回答 2

1

您不能对这种情况应用锁定,因为导入不能以这种方式工作。导入的模块只执行一次,即第一次导入。后续导入仅从 复制现有引用sys.modules。您将需要弄清楚您的实际问题是什么,然后提出问题。

于 2012-10-15T06:23:20.280 回答
0

您还可以检查实例是否已存在,如果存在则引发错误:

In [1]: import gc

In [2]: class Foo(object):
   ...:     pass

In [3]: bar=Foo()

In [4]: [item for item in gc.get_referrers(Foo) if isinstance(item,Foo)]
Out[4]: [<__main__.Foo at 0x187cc90>]

使用any([isinstance(item,Foo) for item in gc.get_referrers(Foo)]),如果为真,则引发异常。

于 2012-10-15T07:05:54.437 回答