How do I access a variable in one python script from another script

Viewed 36

bot2.py

from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse


app = Flask(__name__)


@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    constparam = incoming_msg

    print(constparam)
    msg.body(constparam)

    return str(resp)


if __name__ == '__main__':
    app.run()

dummy.py

from bot2 import app,bot
import time

while 1:

    print(bot.constparam)
    time.sleep(5)

I want to use constparam variable of bot2.py in dummy.py

1 Answers

I'm not familiar with how Flask exposes its instances, but normally, any top-level variable or object can be imported and accessed. However, since bot is a function, all of its variables (including constparam) are private and only accessible within that function. One thing that you can do is to make constparam a global variable instead, where it can be accessed from any module that imports the file. Since you would start by setting the variable, you first will have to add a global constparam to the bot function before anything else to do with constparam occurs.

Related