0

I'm writing a code in which inside of it I need to run another python file which I have the path for it , and to save its output ( the exception it returns or the output it self ). Can someone guide me ? I tried subprocess but it doesn't run :

import subprocess    
output = call ('python' , filePath)

thanks in advance

  • 1
    Did you read the documentation of ``subprocess``? For that matter, did you read the documentation in general (the code shown does not correctly import ``subprocess.call``)? Note that [``subprocess.run``](https://docs.python.org/3/library/subprocess.html#subprocess.run) and [``subprocess.check_output``](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) are more appropriate for what you intend to do. – MisterMiyagi Sep 16 '20 at 14:17
  • Does this answer your question? [What is the best way to call a script from another script?](https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script) – Tomerikoo Sep 16 '20 at 14:33

1 Answers1

1

Short answer is don't. This is not the intended way to call python code from another python program.

If you want to run functionality from a second python function you should import the other file and call a function.

For example

#MainProg.py
import OtherProg

result = OtherProg.add(2,2)
print(result)

.

#OtherProg.py
def add(num1, num2):
    return num1 + num2
scotty3785
  • 6,763
  • 1
  • 25
  • 35
  • 1
    There are many Python programs that are not suitable for import by other programs – either because they would interfere with the program state (e.g. library versions) or only expose a CLI. – MisterMiyagi Sep 16 '20 at 14:22