我有以下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 的了解不足,任何帮助将不胜感激!
提前谢谢你!
这也不是你问题的答案,我可能会得到数百个负面点,这是你没有问到的问题的答案,»我怎么能等待并行陈述的许多过程?
#!/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
。我的意思是。。。随意创建自己的异常,但在这种特殊情况下,您不需要类,(此外,在循环中定义类是一种不好的做法)