Skip to main content
 首页 » 编程设计

python之在 Python 中,为什么不能在使用 subprocess 创建文件后立即对其进行解析

2025年05月04日14dyllove98

我正在尝试读取一个输入文件(下面列为“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') 

第二个 block 产生这个错误: IOError: [Errno 2] 没有这样的文件或目录:'CreateFile.txt' python解释器不会等到上一行完成吗?

请您参考如下方法:

来自 documentation -

Execute a child program in a new process.

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

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

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

或者你也可以使用subprocess.call()如果您想做的就是运行命令(如果您的情况与您发布的代码一样简单,建议通过 Popen 使用此命令)。来自 documentation为此-

Run the command described by args. Wait for command to complete, then return the returncode attribute.

例子-

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