python,只在函数或进程中添加中断一次



>我有包含文件扩展名.java,.c和.cpp的文本文件。 script.py 正在工作,但如何在函数中添加中断? 如果脚本正在处理 test1.txt,我希望它只针对该特定文件转到操作 1 和操作 2 一次。

测试.txt

abc/sas/.java

测试1.txt

abc/sas/.java
abc/asfa/.java
def/def/.c
e/e/.cpp
e/fa/.cpp

script.py

PWD1 = PWD + "/folder"
set = ""
files = glob.glob(PWD1 + '/' + '*.txt')
def action1():
print("ACTION1")
def action2():
print("ACTION2")
strings = {'.java': action1, '.c' or '.cpp': action2}
for f in files:
with open(f, 'r') as file:
for line in sorted(file):
print(line)
for search, action in strings.items():
if search in line:
action()

您需要跟踪正在执行的操作,以便只执行一次操作 1,操作 2 一次,然后爆发。

如果我理解正确,下面的代码应该可以工作。

for f in files:
a1 = False
a2 = False
with open(f, 'r') as file:
for line in sorted(file):
if a1 is False and '.java' in line:
action1()
a1 = True
elif a2 is False and ('.cpp' in line or '.c' in line):
action2()
a2 = True
if a1 and a2:
break

两件事:

首先,要回答您的问题,您可以执行以下操作:

ext_to_actions = {'java': action1, 'c': action2, 'cpp': action2}
for f in files:
performed_actions = set()
with open(f, 'r') as file:
for line in sorted(file):
print(line)
file_ext = line.split('.')[-1]
if file_ext in ext_to_actions:
action = ext_to_actions[file_ext]
if action not in performed_actions:
action()
performed_actions.add(action)

这样做是通过跟踪set中执行的操作并防止您重复操作来消除多次执行操作的功能。

其次,你的字典不会像你预期的那样表现。

>>> strings = {'.java': action1, '.c' or '.cpp': action2}
>>> strings
{'.java': action1, '.c': action2}

这是因为当您创建strings字典时,您实际上是要求 python 以编程方式在'.c' or '.cpp'之间进行选择。 请参阅以下代码片段以了解 python 如何解释这一点:

>>> '.c' or '.cpp'
'.c'

你想要的是以下内容...

strings = {'.java': action1, '.cpp': action2, '.c': action2}

展开内部循环并在最后添加 break 语句?或者使用标志。删除"or '.cpp'"or不应该在这样的字典中使用。基本上'.c' or '.cpp'评价".c",但风格不好。可能你的意思是"结束"而不是在?

最新更新