Python Forum
Execute a file within another Python file in Spyder - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Execute a file within another Python file in Spyder (/thread-10878.html)



Execute a file within another Python file in Spyder - Antonio - Jun-11-2018

So I need to run a file (file_1.py) within another file (file_2.py), and use the variables/outputs that are created via file_1.py in file_2.py! In file_2.py, I have tried the followings:

import file_1
exec(file_1)
but non of these work! Could you tell me how I could do such a thing in Spyder?


RE: Execute a file within another Python file in Spyder - snippsat - Jun-11-2018

(Jun-11-2018, 06:46 PM)Antonio Wrote: but non of these work! Could you tell me how I could do such a thing in Spyder?
This is Python feature so nothing special for Spyder or any other editor.
# file1.py
import random

def rand_numb():
    return random.randint(1, 100)
# file2.py
import file1

def foo():
    v = 42
    print(f'The answer to everything is {v} and a random number {file1.rand_numb()}')

foo()
Output:
The answer to everything is 42 and a random number 94