Prasanna Kumar
Prasanna Kumar

Reputation: 69

How to run a particular python script present in any other directory after a "if" statement in a python script?

I need to know how to run a python script from a python script present in other directory like the following algorithm:

if option==true
 run /path/to/the/directory/PYTHON SCRIPT
else

Upvotes: 0

Views: 309

Answers (4)

furkle
furkle

Reputation: 5059

ch3ka points out that you can use exec to do this. There are other ways like subprocess or os.system as well.

But Python works well with itself by design - this is the entire concept behind creating and importing modules. I think for most cases you'd be better off just encapsulating the script in a class, and moving the code that was previously in the if __name__ == '__main__' section of the script into the __init__ section of the class:

class PYTHON_SCRIPT:
     def __init__(self):
         # put your logic here

Then you could just import the class:

import PYTHON_SCRIPT

# no need to say if a boolean is true, just say if boolean
if option:
    PYTHON_SCRIPT()

This would additionally give you the benefit of being able to use properties within your script as you saw fit.

Upvotes: 1

Ludovic Viaud
Ludovic Viaud

Reputation: 202

if the script is well designed it probably just launch a main function (often called main), so the most proper way to do this is to import this main function in your code and call it, this is the pythonic way. You just need to add the directory of the script into your python path.

if it's possible, always try to avoid exec, subprocess, os.system, Popen etc ..

example :

import sys
sys.path.insert(0, 'path/to/the/directory')
import python_script
sys.path.pop(0)

if option:
    python_script.main()

Upvotes: 0

Vasif
Vasif

Reputation: 1413

Already answered here How do I execute a program from python? os.system fails due to spaces in path

use subprocess module

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

other methods include making system calls using os library or execfile in the other post

Upvotes: 0

ch3ka
ch3ka

Reputation: 12158

use execfile.

execfile(...) execfile(filename[, globals[, locals]])

Read and execute a Python script from a file.
The globals and locals are dictionaries, defaulting to the current
globals and locals.  If only globals is given, locals defaults to it.

In pyton3, execfile is gone. You can use exec(open('/path/to/file.py').read()) instead.

Upvotes: 0

Related Questions