0

我有一个看起来像这样的python代码:

    os.system("...../abc.bat")
    open("test.txt")
    .....

abc.bat 在完成运行后创建 test.txt 的位置。现在的问题是,由于这里没有“等待”,代码直接转到 open("file.txt") 并且自然找不到它,因此出现了问题。

如果 bat 运行已经完成并且现在 python 可以移动到 open("test.txt"),有什么方法可以找出状态?

注意:我使用了一个想法,在 bat 文件中的命令类型为 nul>run.ind,并且该文件在最后被 bat 文件删除,作为 bat 运行已完成的指示。我可以在 python 代码中以某种方式使用它,例如:

    os.system("...../abc.bat")
    if file run.ind exists == false:
        open ("test.txt")

这似乎有些粗糙。有没有其他更简单的方法可以做到这一点?或者换句话说,是否可以引入一些“等待”直到蝙蝠运行完成?

4

4 回答 4

4

我不确定os.system所有平台上的等待语义,但您可以只使用文档指向的subprocess.call() ;os.system

运行 args 描述的命令。等待命令完成,然后返回 returncode 属性。

于 2013-08-07T10:18:52.923 回答
1

也许你可以尝试把它放在一个while循环上。

import os
import time

os.system("...../abc.bat")

while True:
    try:
        o = open("test.txt", "r")
        break
    except:
        print "waiting the bat.."
        time.sleep(15) # Modify (seconds) to se sufficient with your bat to be ready
        continue
于 2013-08-07T11:31:03.300 回答
0

您可以创建一个循环并尝试在循环内重命名文本文件(为其自身)。这只会在文本文件完成时成功。

于 2015-02-08T03:30:06.477 回答
0

回答一个老问题,但它可能对来到这里的新人有所帮助

我已经实现了一个等待事情的python包

https://pypi.org/project/wait-for-it-to/

像这样安装:

pip install wait-for-it-to

并在您的示例中像这样使用

import os
import wait_For_it_to

os.system("...../abc.bat")

wait_for_it_to.be_true(os.path.exists, timeout=60,args=['test.txt'])
于 2020-12-28T20:03:25.500 回答