2

At the end of the execution of the following script, I receive some errors like these:

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: 

It seems like Popen is trying to close the file at the end of execution, although it was removed.

#!/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)

How can I close the file properly?

Thanks.

superNobody
  • 57
  • 1
  • 6

3 Answers3

3

it sounds like your subprocess executes, but since it is non-blocking, your os.remove(infile) executes immediately after, deleting the file before the subprocess finishes.

you could use subprocess.call() instead, which will wait for the command to finish.

... or you could change your code to use wait():

p = subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
p.wait()
os.remove(infile)
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
0

You can also use this.

ss=subprocess.Popen(FileName,shell=True)
ss.communicate()
imp
  • 1,967
  • 2
  • 28
  • 40
0

You could try running the subprocess.Popen in a thread, and just deleting the file after the subprocess call returned.

see: Python subprocess: callback when cmd exits

Community
  • 1
  • 1
Gerrat
  • 28,863
  • 9
  • 73
  • 101