在 Python 中,为什么不能在使用子进程创建文件后立即解析文件?



我试图读取一个输入文件(下面列出的'infile2',它可以是任何文件),并在这个文件中的每一行,使File2,然后解析File2使File3。不管我为什么想要这样编码(当然,除非这是一个问题的原因……),为什么第一个代码块可以工作,而下一个失败?

#!/usr/bin/env python
import sys
import subprocess
#THIS WORKS
def CreateFile():
    command = "echo 'Here is some text' > CreateFile.txt"
    subprocess.Popen(command,shell=True)
def Parse():
    with open("CreateFile.txt") as infile1:
        for line in infile1:
            return line
if __name__ == '__main__':
    infile2 = sys.argv[1]
    with open(infile2) as f:
        for line in f:
            CreateFile()
    with open(infile2) as g:       
            print Parse()
            outfile=open("CreateFile.txt",'w')

,

#!/usr/bin/env python
import sys
import subprocess
def CreateFile():
    command = "echo 'Here is some text' > CreateFile.txt"
    subprocess.Popen(command,shell=True)
def Parse():
    with open("CreateFile.txt") as infile1:
        for line in infile1:
            return line
if __name__ == '__main__':
    infile2 = sys.argv[1]
    with open(infile2) as f:
        for line in f:
            CreateFile()    
            print Parse()
            outfile=open("CreateFile.txt",'w')

第二个块产生如下错误:error: [Errno 2]没有这样的文件或目录:' createffile .txt'python解释器不等待直到前一行完成吗?

From documentation -

在新进程中执行子程序。

Popen启动进程并继续主线程的执行。您看到的问题很可能是因为您使用Popen发出的命令在您试图打开CreateFile.txt时尚未完成。这在第二个脚本中更明显,因为您试图在发出命令后立即打开CreateFile.txt,而在第一个脚本中,在这两个操作之间有一些语句。

尝试使用Popen的.wait()方法,等待进程完成后再执行命令,示例-

def CreateFile():
    command = "echo 'Here is some text' > CreateFile.txt"
    subprocess.Popen(command,shell=True).wait()

或者你也可以使用subprocess.call(),如果你想做的就是运行命令(如果你的情况像你发布的代码一样简单,我会推荐使用Popen)。-

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

,

def CreateFile():
    command = "echo 'Here is some text' > CreateFile.txt"
    subprocess.call(command,shell=True)

python解释器不等待直到上一行完成吗?

如果前一行是:subprocess.Popen(command,shell=True)

Popen()创建异步进程并立即返回。如果您想等待进程完成,请尝试subprocess.call()subprocess.check_call

您正在使用subprocess.Popen创建文件,这将启动一个新进程。在此之后,继续执行,并且您已经尝试打开正在创建的文件。

您应该等待子进程完成。您可以使用Popen对象的.wait()方法来执行此操作。

最新更新