Tyler Sanderson
Tyler Sanderson

Reputation: 93

When I use os.system() to open a .py file in Python it automatically closes it immediately. How do I fix this?

I'm writing a script that needs to open another script, but continue running the main script such that both scripts are running simultaneously.

I've tried execfile() but the file doesn't open. When I use os.system(somefile.py) it successfully opens the .py file via console but immediately closes it. Are there alternatives so that I can run a python script within a main python script, but have both processes running simultaneously without conflicting one another?

Here is sample code I've tested:

import os
file_path = 'C:\\Users\\Tyler\\Documents\\Multitask Bot\\somefile.py'

def main():
    os.system(file_path)

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 4402

Answers (3)

User
User

Reputation: 14873

Your problem can be that that file is not executed in C:\\Users\\Tyler\\Documents\\Multitask Bot\\ but somewhere else. The local import may fail.

could you try executing os.chdir('C:\\Users\\Tyler\\Documents\\Multitask Bot\\') before os.system ?

Upvotes: 0

mhawke
mhawke

Reputation: 87124

execfile() and os.system() will block the parent process until the child exits. Use subprocess.Popen(), e.g.

import subprocess, time
file_path = 'C:\\Users\\Tyler\\Documents\\Multitask Bot\\somefile.py'

def main():
    child = subprocess.Popen(['python', file_path])
    while child.poll() is None:
        print "parent: child (pid = %d) is still running" % child.pid
        # do parent stuff
        time.sleep(1)
    print "parent: child has terminated, returncode = %d" % child.returncode

if __name__ == '__main__':
    main()

This is just one way to handle it. You may want to collect stdout and/or stderr from the child and possibly send data to the child's stdin. Read up on the subprocess module.

Upvotes: 3

Neil
Neil

Reputation: 2438

If you want to run another script simultaneously, consider the subprocess module.

Upvotes: 2

Related Questions