示例:
test.py
class test_class(object):
def display(self):
print "Hello"lock1.py
from test import test_class
from time import sleep
obj = test_class()
while True:
obj.display()
sleep(1)lock2.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我需要做的是锁定(或任何)文件锁2.py的类(或整个test.py),如果对象在引发错误(或支出)之前已经为该类初始化了。我简化了这个例子,尽管这个例子看起来可能不相关。
我试着用以下方法锁定文件,即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 accessing_file1.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 = 0accessing_file2.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并检查rest文件,那么我所做的就是创建一个db标志。如果comm_port很忙,其他访问文件将无法工作。但我认为这不是最好的做法。
因此,我需要检查是否有一种方法来检查CommPort类是否是由任何对象或通过锁定comm_port.py或任何其他现有想法来激发的。
发布于 2012-10-15 06:23:20
您不能在这种情况下应用锁,因为导入不是这样工作的。导入的模块只在第一次导入时只执行一次。后续导入仅从sys.modules复制现有引用。你需要弄清楚你的实际问题是什么,然后去问这个问题。
发布于 2012-10-15 07:05:54
还可以检查实例是否已经存在,如果存在则引发错误:
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)]),如果是真的话,那就大声说出来。
https://stackoverflow.com/questions/12890202
复制相似问题