whanwhan
whanwhan

Reputation: 3

run another .py file when condition is true

I'm very new to Python and trying to make a small project in Raspberry Pi2 with Python

Currently I have 2 code files run1.py and run2.py

I would like to write an if-else condition in Project.py but I'm not sure how to write the code properly....

if (condition is true) ----> run the code from file "run1.py"
else ----> run the code from file "run2.py"

Is it about the topic of '__main__' or import os? i'm trying to understand how it works too but not really understand yet.

Thank you

Upvotes: 0

Views: 8545

Answers (4)

MaestroHCC
MaestroHCC

Reputation: 11

I think runpy is better, imagine you have 25 classes, and they are significantly different from each other. It is not nice, to make 25 import statements around 25 if conditions on your code.

Folder:.
    preA.py
    preB.py
    preC.py
    preD.py
    test.py

You could use a function that saves you time, and preserves your clean code

import runpy

def call_f(filename):

    return runpy.run_path(filename , run_name='__main__')

#Call the function, since we are using run_path we have to specify the extension
#You can also use modules and you should use runpy.run_module
res = call_f('preA.py')

print(res['res'])
#>> 0

And the preprocessing file would look like this:

def preproc():

    print('I am A preprocessing, different from any other type of preprocessing')

    return 0

if __name__ == '__main__':

    res =  preproc()

Upvotes: 0

pythondetective
pythondetective

Reputation: 336

if <condition>: 
    run1.py
else:
    run2.py

If condition is true then run1.py will run. Otherwise run2.py will run.

I hope I answer your question.

Upvotes: -2

allo
allo

Reputation: 4236

I would recommend that way:

main.py

import first, second
if __name__ == "__main__":
  if foo:
    first.main()
  else:
    second.main()

first.py:

def main():
  do_something()
if __name__ == "__main__":
  main()

second.py (just like first.py)

You can then call first.py / second.py from the command line and they run their code. If you import them (import first, second) they do nothing, but you can call their (main)methods, i.e. in your if-else-condition.

The __name__ == "__main__" part prevents the code in the condition to run when its imported from another file, while it runs when the file is executed directly from the commandline.

Upvotes: 0

Colin Emonds
Colin Emonds

Reputation: 797

If you just want to import one of the files, for example because both of them have a function called foo and you want to pick one of them at runtime, you can do this:

if condition:
    import fileA as file
else:
    import fileB as file
file.foo()

If you actually need to start the files (they are independent programs), you can do this:

import subprocess
if condition:
    subprocess.call(['python', 'fileA.py'])
else:
    subprocess.call(['python', 'fileB.py'])

Upvotes: 5

Related Questions