Python中断while循环+异常

2024-09-23 00:14:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的python代码,它是为运行名为cctfiles的fortran代码而设计的。然后我用abedin对正在运行的进程进行快照,并将快照写入名为sample.txt的文件。然后我读取文件sample.txt,直到运行的进程./cctfiles从文件中消失。但是我注意到,即使程序cctfiles已经退出,我的python代码也不会从while循环中中断。 下面是我的代码:

#!/usr/bin/env python


import subprocess

scb = subprocess.call



def runprog(name):
        for i in xrange(1,2):
                scb('cp '+name+' '+str(i), shell = 'True')
                scb('sleep 1', shell = 'True')
                scb('(cd '+str(i)+';'+' ./'+name+' &)', shell = 'True')
                print('Job '+str(i)+' has been sent:')
#               scb('cd ../', shell = 'True')

        while True:
                scb('sleep 5', shell = 'True')
                scb('ps -ef | grep abedin > sample.txt', shell = 'True')
                cnt = subprocess.Popen('grep -c ".*" sample.txt',stdout=subprocess.PIPE, shell = 'True')
                (c,err) = cnt.communicate()
                nlines = int(c.strip())
                fl = open('sample.txt', 'r+')
                count = 0
                class BreakIt(Exception): pass
                try:
                        for line in fl:
                                count = count + 1
                                for word in line.strip().split():
#                                       print(word.strip())
                                        if word.strip() != './'+name and count == nlines:
                                                raise BreakIt
                except BreakIt:
                        pass

                else: break

            fl.seek(0)
            fl.truncate()
            fl.close()
    print('----------Finaly Done------------')


runprog('cctfiles')

鉴于我对Python的了解很差,任何帮助都将不胜感激!在

提前谢谢你!在


Tags: sample代码nameintxttrueforcount
2条回答

而且,这不是你问题的答案,我可能得到数百个否定点,这是你未被问到的问题的答案,»我怎么能等待许多过程同时陈述?«

#!/usr/bin/env python
import os
import subprocess

def runprog(name):
    processes = [subprocess.Popen([os.path.abspath(name)], cwd=str(i)) for i in xrange(1,2)]
    for process in processes:
        process.wait()
    print('     Finaly Done      ')

runprog('cctfiles')

因此,当您的try/except块接收到BreakIt异常时,它不会做任何事情。因为BreakIt位于while True循环内,所以它一直循环。然后你break对每一个不是的异常BreakIt一个。听起来你想做相反的事。在

您可能需要将try/except更改为:

while True:
    scb('sleep 5', shell = 'True')
    count = 0
    # [ . . . ]
    class BreakIt(Exception): pass
    try:
        for line in fl:
        # [ . . . ]
    except BreakIt:
        break
    else: 
       # Do stuff with not BreakIt exceptions

另外:我强烈建议使用内置的StopIteration,而不是你的BreakIt。我是说。。。您可以随意创建自己的异常,但在这种特殊情况下,您不需要该类(而且,在循环中定义类是一种不好的做法)

相关问题 更多 >