deniska369
deniska369

Reputation: 241

Python twice opens a file if uses subprocess.Popen for run another script

I have script test1.py (For example)

import test2


def main():
    f = open("File.txt")
    test2.run()

    while True:
        pass

if __name__ == '__main__':
    main()

And test2.py

import subprocess, sys, os

def run():
    # Self run
    subprocess.Popen(['C:\\Windows\\System32\\cmd.exe', '/C', 'start',
                          sys.executable, os.path.abspath(__file__)])

def main():
    while True:
        pass

if __name__ == '__main__':
    main()

The problem is that the startup of the second script re-open the file "File.txt". Why is the second script at startup opens the file?

D:\test>Handle.exe File.txt

Handle v4.0
Copyright (C) 1997-2014 Mark Russinovich
Sysinternals - www.sysinternals.com

python.exe         pid: 9376   type: File           29C: D:\test\File.txt
python.exe         pid: 9792   type: File           29C: D:\test\File.txt

Upvotes: 2

Views: 1735

Answers (2)

holdenweb
holdenweb

Reputation: 37103

By the time you call test2 your test1 program has already opened the file. Therefore, when you create a subprocess that child process inherits any open files - including File.txt.

See the notes on file inheritance in the documentation for subprocess.

Upvotes: 1

Owen
Owen

Reputation: 1547

The child process inherits a file handle for compatibility with the Unix model (see PEP 446 for more explanation). After the subprocess call, both the original and the new script should have access to the file; on Windows that means two separate file handles open.

A better idiom if you want to avoid this is to close the file before forking, either explicitly or using the with construct:

with open('File.txt', 'r') as inputfile:
    pass # or do something with inputfile

Upvotes: 1

Related Questions