Python Forum
Execute a file within another Python file in Spyder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Execute a file within another Python file in Spyder
#1
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?
Reply
#2
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to remove unwanted images and tables from a Word file using Python? rownong 2 859 Feb-04-2025, 08:30 AM
Last Post: Pedroski55
  Locally run an APK and execute functions using Python KovyJ 0 507 Jan-23-2025, 05:21 PM
Last Post: KovyJ
  Best way to feed python script of a file absolut 6 1,237 Jan-11-2025, 07:03 AM
Last Post: Gribouillis
  Removal of watermark logo pdf file Python druva 0 798 Jan-01-2025, 11:55 AM
Last Post: druva
  How to write variable in a python file then import it in another python file? tatahuft 4 1,008 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  How to communicate between scripts in python via shared file? daiboonchu 4 1,943 Dec-31-2024, 01:56 PM
Last Post: Pedroski55
  Problems writing a large text file in python Vilius 4 1,090 Dec-21-2024, 09:20 AM
Last Post: Pedroski55
  How to re-register .py file extension to new moved Python dir (on Windows)? pstein 5 1,442 Nov-06-2024, 03:06 PM
Last Post: DeaD_EyE
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 1,137 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  FileNotFoundError: [Errno 2] No such file or directory although the file exists Arnibandyo 0 1,138 Aug-12-2024, 09:11 AM
Last Post: Arnibandyo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020