[英]how to check file is opened from python scrip
我需要检查文件是否在 perforce 中打开,如下所示:
if((p4.run("opened", self.file) != True):
但这不是正确的方法,我认为它总是正确的,请您帮忙解决这个问题谢谢
p4.run("opened")
返回与打开文件对应的结果列表(dicts),如果在您提供的路径规范内没有打开文件,则该列表将为空。 尝试打印出该值,或者更好地在 REPL 中运行它,以更好地了解 function 返回的内容:
>>> from P4 import P4
>>> p4 = P4()
>>> p4.connect()
P4 [Samwise@Samwise-dvcs-1509687817 rsh:p4d.exe -i -r "c:\Perforce\test\.p4root"] connected
>>> p4.run("opened", "//...")
[{'depotFile': '//stream/test/foo', 'clientFile': '//Samwise-dvcs-1509687817/foo', 'rev': '2', 'haveRev': '2', 'action': 'edit', 'change': 'default', 'type': 'text', 'user': 'Samwise', 'client': 'Samwise-dvcs-1509687817'}]
>>> p4.run("opened", "//stream/test/foo")
[{'depotFile': '//stream/test/foo', 'clientFile': '//Samwise-dvcs-1509687817/foo', 'rev': '2', 'haveRev': '2', 'action': 'edit', 'change': 'default', 'type': 'text', 'user': 'Samwise', 'client': 'Samwise-dvcs-1509687817'}]
>>> p4.run("opened", "//stream/test/bar")
[]
我们可以看到运行p4 opened //stream/test/foo
给了我们一个包含一个文件的列表(因为foo
已打开以进行编辑),而p4 opened //stream/test/bar
给了我们一个空列表(因为bar
不是对任何事物开放)。
在 Python 中,如果列表为空,则列表为“假”,如果非空,则列表为“真实”。 这与== False
和== True
不同,但它确实适用于大多数其他需要 boolean 的上下文,包括if
语句和not
运算符:
>>> if p4.run("opened", "//stream/test/foo"):
... print("foo is open")
...
foo is open
>>> if not p4.run("opened", "//stream/test/bar"):
... print("bar is not open")
...
bar is not open
以这种方式使用列表被认为是完全 Pythonic 的(这就是语言中存在“真实性”概念的原因)而不是使用显式的True
/ False
值。
如果您确实需要准确的True
或False
值(例如,从声明为返回准确 boolean 值的 function 返回),您可以使用bool
ZC1C425268E68385D1AB5074C17A94F 将 true 值转换为True
和False
>>> bool(p4.run("opened", "//stream/test/foo"))
True
>>> bool(p4.run("opened", "//stream/test/bar"))
False
或使用len()
比较,这相当于同一件事:
>>> len(p4.run("opened", "//stream/test/foo")) > 0
True
>>> len(p4.run("opened", "//stream/test/bar")) > 0
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.