Using Variables from Imported files in Python - python

I am trying to get a variable and its value from another python file that has been Imported . I have the file Main.py and Write.py .In the Main file I am trying to get the variable user_id to equal the new_id variable from the Imported file Write.py .The new_id is creating a hash for the new user when they scan their tag (rfid). The issue is after the tag is scanned the Variable user_id still remains empty. I think I might be grabbing the variable before the tag is scanned, any thoughts? I have posted the code below along with some comments.
from tkinter import *
#Second File
import Write
from tkcalendar import DateEntry
from firebase import firebase
data = {}
global user_id
# Firebase
firebase= firebase.FirebaseApplication("https://xxxxxxx.firebaseio.com/",None)
# button click
def sub ():
global user_id
#setting Variables from user input
name = entry_1.get()
last = entry_2.get()
number = phone.get()
# issue is here
try:
#Calling Function from other file
Write.scan()
if Write.scan():
#getting the New User Id
user_id= new_id
#User Info being sent to the Database
data = {
'Name #': name,
'Last': last,
'Number': number,
'Card #':user_id
}
results = firebase.post('xxxxxxxx/User',data)
except Exception as e:
print(e)
Write.py
import string
from random import*
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()
#Function being called
def scan():
try:
#Creating user hash
c = string.digits + string.ascii_letters
new_id = "".join(choice(c) for x in range(randint(25,25)))
print("Please Scan tag")
#Writing to tag
reader.write(new_id)
if reader.write(new_id):
print("Tag Scanned")
else:
print("Scan Tag First")
print("Scanning Complete")
finally:
GPIO.cleanup()

Not sure if this is the actual issue or just the formatting in here, but your indentations for the try: statement are wrong in your main file.

Related

How to pass a variable from one function to another function

I am making python based Email broadcasting in which i have created entries like email, pass, there is csv browse as well which will brose a Email_list_container file and a submit button which will call a send mail function to send bulk email along with attachment, problem is when browse is used to grab emails from csv it stores to a variable and then return to function but when I call this variable in send mail function is does not allow me to use it there. same with attachment function is is not coming in send mail function either.
i have tried Global
newvar = browse()
and calling new var but this calls whole function to pop-up again new window to open another file which does not make any sense.
help me guys.
from tkinter import *
import tkinter.messagebox as msg
import smtplib as smtp
import csv
from itertools import chain
#browse function which stores value from csv file
def browse():
from itertools import chain
file_path=filedialog.askopenfilename(title="Open CSV file")
with open(file_path) as csvfile:
read = csv.reader(csvfile)
for row in read:
ini_list.append(row)
flatten_list = list(chain.from_iterable(ini_list))
rcvr_emails =list(flatten_list)
# print(rcvr_emails)
file_label = Label(window,text=file_path, border=0, bg='#BAE1E3',font="inter 10", fg="grey").place(x=330,y=230)
recemail = rcvr_emails
#what i want is submit function to grab a variable from browse function as email list
def submit():
try:
email = login_email.get()
pass_word = login_pass.get()
subject = email_subject.get()
body = email_body.get()
server = smtp.SMTP("smtp.gmail.com",587)
server.starttls()
server.ehlo()
server.login(email,pass_word)
massage = "subject:{}\n\n{}".format(subject,body)
server.sendmail(email,recemail,massage)
server.quit()
msg.showinfo("Status","Mails have been sent to the Targatted Email's List.\nThank You for using our services.")
except:
msg.showwarning("ERROR","SMTP API could not login the credentials,\nPlease check Email & Password then try again.")
Just return recemail from browse function then pass it as argument to submit function:
def browse():
from itertools import chain
file_path=filedialog.askopenfilename(title="Open CSV file")
with open(file_path) as csvfile:
read = csv.reader(csvfile)
for row in read:
ini_list.append(row)
flatten_list = list(chain.from_iterable(ini_list))
rcvr_emails =list(flatten_list)
# print(rcvr_emails)
file_label = Label(window,text=file_path, border=0, bg='#BAE1E3',font="inter 10", fg="grey").place(x=330,y=230)
recemail = rcvr_emails
return recemail
def submit(email_list):
// your code
Then in your main program:
received_email = browse()
submit(received_email)
Or in one line:
submit(browse())

Configparser writes to fie but returns empty result

So this function is a cut-out, from a class that should create and then extract information from an ini file. The problem I have is that the ini file definitely shows that all the added sections exist, but whenever I want the program to extract information or read from the file, it returns [], an empty list. I tried this function in a more basic version using Anaconda Navigator, well it turned out there it worked.
The screenshot shows the ini file.
As seen in the screenshot, the file is indeed not empty and the function successfully wrote to it, problem is whenever the function should print from it or when I want another function to read it, it returns [].
Code is as following:
class cSetup():
import os
import time
import datetime
import configparser as configparser
"""Class creates an ini file, this ini file contains a number of settings which can be read by the get function.
the program will later access this file to check for certain settings.
If the file is not existing yet, a function within the class will create it
"""
config = configparser.ConfigParser()
def write_setup(self):
if os.path.exists("Setup.ini"):
setup_file = open("Setup.ini", "r")
print(self.config.read(setup_file))
setup_file.close()
else:
"""This function is the initial setup, it writes all the necessary information to a .ini file."""
global config
"""Asks user for a name"""
Name = input("Please enter your name, note this can be changed in the settings""\n"
"Please enter the name here: ")
self.time.sleep(1)
"""asks user for prefered input method"""
PreferredInput = input("Input method required: 0 Shutdown, 1 Voice Commands, 2 Text Commands, 3 Dev Mode: ")
setup_file = open("Setup.ini", "w")
setup_file
self.config.write(setup_file)
self.config.add_section("Setup state")
self.config.set("Setup state", "Activated?", "True") # Convert to Bool later
section_option = "Settings"
self.config.add_section(section_option)
self.config.set(section_option, "Name", Name)
self.config.set(section_option, "Preferred Input", PreferredInput) # Convert to int later
self.config.write(setup_file)
setup_file = open("Setup.ini", "r")
print(self.config.read(setup_file))
setup_file.close()

Python try finally statement to run another file

I am having an issue getting my try and finally statement to execute properly. I am trying to get another Python file to execute once a user has interacted with the first program.For example, once the first program is run the user will be asked to scan their tag which will create a unique user id for that user; after their tag is scanned a second python file will be executed. My problem is that the second file is constantly being run as soon as the first file is executed regardless if the tag is scanned first or not. I have added my code below with comments to help explain better. Any thoughts?
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
# Second File being ran
import medform
reader = SimpleMFRC522()
try:
# user id being created
c = string.ascii_letters + string.digits
op = "".join(choice(c) for x in range(randint(8,16)))
# Printed before tag is scanned
print("Please Scan tag " )
reader.write(op + op)
# if tag is scanned / id created open second file
if reader.write(op + op):
os.system('python medform.py')
else:
print("Scan Tag First" )
# Print after tag is scanned
print("Scan Complete")
finally:
GPIO.cleanup()
importing a file runs it, there are 2 ways to do what you want:
import the file when you want it to run
define a main function in the other file that you can run from the first one instead of having all the code in the top level
the second option is the best one in most cases, as you normally would not want a file to actually do stuff on import.
so in the second file you would have:
def main():
# the code you want to run (make sure to indent it)
then in the first you can have:
import medform
# ...
medform.main()

Getting file input into Python script for praw script

So I have a simple reddit bot set up which I wrote using the praw framework. The code is as follows:
import praw
import time
import numpy
import pickle
r = praw.Reddit(user_agent = "Gets the Daily General Thread from subreddit.")
print("Logging in...")
r.login()
words_to_match = ['sdfghm']
cache = []
def run_bot():
print("Grabbing subreddit...")
subreddit = r.get_subreddit("test")
print("Grabbing thread titles...")
threads = subreddit.get_hot(limit=10)
for submission in threads:
thread_title = submission.title.lower()
isMatch = any(string in thread_title for string in words_to_match)
if submission.id not in cache and isMatch:
print("Match found! Thread ID is " + submission.id)
r.send_message('FlameDraBot', 'DGT has been posted!', 'You are awesome!')
print("Message sent!")
cache.append(submission.id)
print("Comment loop finished. Restarting...")
# Run the script
while True:
run_bot()
time.sleep(20)
I want to create a file (text file or xml, or something else) using which the user can change the fields for the various information being queried. For example I want a file with lines such as :
Words to Search for = sdfghm
Subreddit to Search in = text
Send message to = FlameDraBot
I want the info to be input from fields, so that it takes the value after Words to Search for = instead of the whole line. After the information has been input into the file and it has been saved. I want my script to pull the information from the file, store it in a variable, and use that variable in the appropriate functions, such as:
words_to_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....
So basically like a config file for the script. How do I go about making it so that my script can take input from a .txt or another appropriate file and implement it into my code?
Yes, that's just a plain old Python config, which you can implement in an ASCII file, or else YAML or JSON.
Create a subdirectory ./config, put your settings in ./config/__init__.py
Then import config.
Using PEP-18 compliant names, the file ./config/__init__.py would look like:
search_string = ['sdfghm']
subreddit_to_search = 'text'
notify = ['FlameDraBot']
If you want more complicated config, just read the many other posts on that.

I can retrieve values from datastore

I want to retrieve some values I put in the data store with a model class name "Ani" and I have tried using the script below to do that but I am having problem with. Can someone please, help me with it
import random
import getpass
import sys
# Add the Python SDK to the package path.
# Adjust these paths accordingly.
sys.path.append('/root/google_appengine')
sys.path.append('/root/google_appengine/lib/yaml/lib')
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
import models
# Your app ID and remote API URL path go here.
APP_ID = 'silasanio'
REMOTE_API_PATH = '/remote_api'
def auth_func():
email_address = raw_input('Email address: ')
password = getpass.getpass('Password: ')
return email_address, password
def initialize_remote_api(app_id=APP_ID,
path=REMOTE_API_PATH):
remote_api_stub.ConfigureRemoteApi(
app_id,
path,
auth_func)
remote_api_stub.MaybeInvokeAuthentication()
def main():
initialize_remote_api()
Meanvalue = []
result = db. ("SELECT * FROM Ani ORDER BY date DESC LIMIT 1")
for res in result:
Meanvalue = res.mean
std_dev = res.stdev
print(mean)
if __name__ == '__main__':
main()
I am getting the error below:
raise KindError('No implementation for kind \'%s\'' % kind)
google.appengine.ext.db.KindError: No implementation for kind 'Ani'
Please, I need some help with it.
Thanks
You need to import the file where you define the class Ani before you can run queries on the data.

Categories

Resources