HackerGamerLV
HackerGamerLV

Reputation: 37

How to get variable from another Python script (Python 3)

I have 2 Python 3.5 scripts, boot.py and about.py. Boot.py is located in /os, but about.py is located in /os/bin. Boot.py starts about.py with os.system(/path/about.py). The problem is that about.py requires variables that are in boot.py, and i dont want to rewrite them all over again. So i need to start about.py in a way that it can read/use the variables in boot.py. If its unclear, i posted the codes down below.

boot.py:

#Boot.py
import os
import subprocess
import socket
import platform
import multiprocessing
import time
import datetime
from random import randint
#Create functions
def cls():
    os.system('cls' if os.name=='nt' else 'clear')
#Set the variables
prj_name = 'boot.py'
prj_build = 1.01
prj_developer = 'RED'
#Bunch of print() and input() commands below

about.py:

#Somehow get the variables and functions defined in boot.py
print('This project is made by ' + prj_developer)
print('Build: ' + prj_build)
print('Launched by: ' + prj_name)

Upvotes: 0

Views: 1758

Answers (1)

Oisin
Oisin

Reputation: 781

Simply import the other file. By doing so the file will be run and the variables defined.

from boot import *
print('This project is made by ' + prj_developer)
print('Build: ' + prj_build)
print('Launched by: ' + prj_name)

I would also recommend putting all code of the other file, that shouldn't run when imported in a if statement (not necessary in this case though):

if __name__ == "__main__":
    pass # only run if file is executed directly (not from importing)

If the boot.py file is the directory above you would write (add a . for every parent directory):

from .. import boot.*

If the boot.py file is the directory above you would write (make sure to put a empty file called __init__.py in any subdirectories you are importing from):

from DIRECTORY.boot import *

Upvotes: 1

Related Questions