子进程中打开的文件
在执行下面这个脚本的最后,我收到了像这样的错误:
filename.enc: No such file or directory
140347508795048:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('filename.enc','r')
140347508795048:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:
看起来Popen在执行结束时试图关闭一个文件,尽管这个文件已经被删除了。
#!/usr/bin/python
import subprocess, os
infile = "filename.enc"
outfile = "filename.dec"
opensslCmd = "openssl enc -a -d -aes-256-cbc -in %s -out %s" % (infile, outfile)
subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
os.remove(infile)
我该如何正确地关闭这个文件呢?
谢谢。
3 个回答
0
你也可以使用这个。
ss=subprocess.Popen(FileName,shell=True)
ss.communicate()
0
你可以试着把subprocess.Popen放在一个线程里运行,然后在这个子进程调用结束后再删除文件。
参考链接: Python子进程:命令结束时的回调
3
听起来你的子进程在执行,但因为它是非阻塞的,所以你的 os.remove(infile)
立刻就执行了,这样在子进程完成之前,文件就被删除了。
你可以用 subprocess.call()
来代替,这样会等命令执行完再继续。
...或者你可以修改你的代码,使用 wait()
:
p = subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
p.wait()
os.remove(infile)