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
  Python openyxl not updating Excel file MrBean12 1 317 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  Python logging RotatingFileHandler writes to random file after the first log rotation rawatg 0 395 Feb-15-2024, 11:15 AM
Last Post: rawatg
  connect sql by python using txt. file dawid294 2 427 Jan-12-2024, 08:54 PM
Last Post: deanhystad
  file open "file not found error" shanoger 8 1,087 Dec-14-2023, 08:03 AM
Last Post: shanoger
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,429 Nov-09-2023, 10:56 AM
Last Post: mg24
  Replace a text/word in docx file using Python Devan 4 3,302 Oct-17-2023, 06:03 PM
Last Post: Devan
  Help creating shell scrip for python file marciokoko 10 1,346 Sep-16-2023, 09:46 PM
Last Post: snippsat
  Need to replace a string with a file (HTML file) tester_V 1 761 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Python Launcher INI File leodavinci1990 1 816 Jul-30-2023, 03:38 PM
Last Post: snippsat
  How can I change the uuid name of a file to his original file? MaddoxMB 2 921 Jul-17-2023, 10:15 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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