bbartling
bbartling

Reputation: 3502

running a .py file from another Python script using os

Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.

How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks

import os

os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')

Upvotes: 1

Views: 6382

Answers (3)

martineau
martineau

Reputation: 123473

You can execute an arbitrary Python script as a separate process using the subprocess.run() function something like this:

import os
import subprocess
import sys

#py_filepath = 'C:/Users/benb/Desktop/flaskEconServer/plots.py'
py_filepath = 'plots_test.py'

args = '"%s" "%s" "%s"' % (sys.executable,                  # command
                           py_filepath,                     # argv[0]
                           os.path.basename(py_filepath))   # argv[1]

proc = subprocess.run(args)
print('returncode:', proc.returncode)

If you would like to communicate with the process while it's running, that can also be done, plus there are other subprocess functions, including the lower-level but very general subprocess.Popen class that support doing those kind of things.

Upvotes: 2

EmilianoJordan
EmilianoJordan

Reputation: 121

You can get the directory of the app.py file by using the following call in app.py

dir_path = os.path.dirname(os.path.realpath(__file__))

then join the file name you want

file_path = os.path.join(dir_path,'plot.py')

Finally your system call

os.system(f'py {file_path}') # if you're on 3.6 and above.
os.system('py %s' % file_path) # 3.5 and below

As others have said sub-processes and multi-threading may be better, but for your specific question this is what you want.

Upvotes: 0

Tom Lubenow
Tom Lubenow

Reputation: 1161

Python has built-in support for executing other scripts, without the need for the os module.

Try:

from . import plots

If you want to execute it in an independent python process, look into the multiprocessing or subprocess modules.

Upvotes: 1

Related Questions