How do I run a .py file from another python file....

I want a program depending upon the option you choose to run a different python program...

Ho do i do this...

I have tried:

import os
if os.path.isfile('file.py'):

and it requires everything to be global....
only when the call line is the only thing in the file does it work perfectly...

9 Years
Discussion Span
Last Post by Arrorn

You can execute it using the os module. In DOS or GNU/Linux, in the command line you can type python code.py to execute a file. So you can try this:

import os
os.system("python othercode.py")

The one problem would be if the user does not have "python" registered as a recognized command. Below is the universal solution which locates the user's python executable and uses a system call to that with its absolute path:

import os
import sys
pyexe = sys.executable  # something like "C:\Python25\python.exe"
os.system('%s othercode.py' % pyexe)

This should be cross-platform compatible. Hope that helped!


I would use module subprocess:

# os.system() does not allow the Python program 
# to run in the background, whereas subprocess does

import subprocess

# remove  "arg1", "arg2" if you don't have any command line args
subprocess.call(["C:/Python25/Python.exe", "Skripta.py", "arg1", "arg2"])

thanks for your help i'll try both out see what works for me....

Thank you so much.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.