I have been trying multiple ways to try and get a variable from file#1 to file#2 but every time I import file#1 to file#2 it seems like file#2 fails to work. I think this is due to file#2 being run in a subprocess in file#1 but I’m not too sure. Is there a way for me to import the variable without this happening or should I do a main file and run the other 2 files from there?
testaction
is the variable I am trying to use in the other file.
Ex:
File#1
def listen_for_command():
global testaction
global keyword_detected
while keyword_detected:
try:
if "weather in" in cortana_input:
testaction = "weather"
city_text = cortana_input.split("weather in", 1)[1].strip()
print(f"Fetching weather for {city_text}")
#weather based on city
weather_info = get_weather_data(city_text)
print(weather_info)
engine.say(weather_info)
engine.runAndWait()
File#2
#import file#1 or from file#1 import testaction causes file#2 to not run
def listen_for_input():
global action, next_action, animation_active
while True:
user_input = input("Enter action: ").strip()
#I want user_input = testaction
This is how I have the files set up running in File#2
# Start the keyword listener in a separate thread
keyword_thread = threading.Thread(target=listen_for_keyword, daemon=True)
keyword_thread.start()
# Wait for the keyword detection before starting the animation script
while not keyword_detected:
time.sleep(1)
animation_thread = threading.Thread(target=lambda: subprocess.run(["python", "animation.py"]))
animation_thread.start()
listen_for_command()
# Once the keyword is detected, start the animation script
1
You seem to use plain functions. Try creating a class in one file you want the variable to be extracted then create a __init__
function to store the var, then create another function to get the variable you have stored.
ex code file 2:
class var_record:
def __init__(self,clock):#clock is just var
self.clock = clock
# it helps to access the clock in
# other sub functions
def get_clock(self):# no additional vars
return self.clock
# that's it for file 2
ex code file1:
""""
import the py file where we have the var stored. note: the class file should be in the same folder as the code to import file
from (class file name)import (classname)
"""
# real code file 1
from clocker import var_tecord as v
a = v(1000)
print(a.get_clock)
output:
1000
Omm prakash Das vii r-30 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.