如何检查文件是否从 python 脚本打开

问题描述

我需要检查文件是否以强制方式打开:

if((p4.run("opened",self.file) != True):

但这不是正确的方式,我认为它总是正确的 你能帮忙解决这个问题吗 谢谢

解决方法

p4.run("opened") 返回与打开文件对应的结果(字典)列表,如果在您提供的路径规范内没有打开文件,则该列表将为空。尝试只打印出值,或者最好在 REPL 中运行它,以便更好地了解函数返回的内容:

>>> 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',"//stream/test/bar")
[]

我们可以看到,运行 p4 opened //stream/test/foo 会给我们一个包含一个文件的列表(因为 foo 是打开进行编辑的),而 p4 opened //stream/test/bar 会给我们一个空列表(因为 {{1} } 不开放任何东西)。

在 Python 中,列表为空时为“falsey”,非空时为“truthy”。这与 bar== False 不同,但它确实适用于需要布尔值的大多数其他上下文,包括 == True 语句和 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 /True 值被认为是完美的 Pythonic(这就是语言中存在“真实性”概念的原因)。

如果您确实需要精确的 FalseTrue 值(例如从声明为返回精确布尔值的函数返回),您可以使用 False 函数来将真值转换为 bool,将假值转换为 True

False

或使用 >>> bool(p4.run("opened","//stream/test/foo")) True >>> bool(p4.run("opened","//stream/test/bar")) False 比较,这等同于:

len()