how to set global variable with subdirectorys - python-3.x

how can i set a global variable, from a other file from other directory?
I would like to take the variable aaid into test.py and
the variable bbid from test.py print in test2.py
Structure:
d:\test\main.py
d:\test\a\test.py
d:\test\b\test2.py
main.py:
# import relevant files
import sys, os, subprocess
while (True):
# The menu
print("MENU")
print(" 1. Librarian")
try:
choice = int(input("Select who you are (choose a number): "))
except ValueError:
print("you have not entered a numerical input! \nplease enter a number")
# Librarian choice
if choice == 1:
while (True):
# Handling Value Error
try:
aaid = input("\nID? :")
except ValueError:
print("Error! Please enter a numerical input")
else:
os.chdir("a/")
subprocess.call('python test.py', shell=True)
break
test.py
print(aaid)
bbid = x500
test2.py
print(bbid)
error:
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(aaid)
NameError: name 'aaid' is not defined
python 3.8.2 on windows 10

Related

Why is this code raising an AssertionError?

This is the code.
# mean_var_std.py
def calculate(list):
try:
if len(list) < 9:
raise ValueError
else:
return 0
except ValueError:
print("List must contain nine numbers.")
This is the test.
import unittest
import mean_var_std
# the test case
class UnitTests(unittest.TestCase):
def test_calculate_with_few_digits(self):
self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])
if __name__ == "__main__":
unittest.main()
When I run it, I get the following output:
F
======================================================================
FAIL: test_calculate_with_few_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/runner/fcc-mean-var-std-2/test_module.py", line 8, in test_calculate_with_few_digits
self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])
AssertionError: ValueError not raised by calculate
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
The output says that the code isn't raising a ValueError, but from the code we can clearly see that the code raises a ValueError. Why is my code still failing the unittest?
It's because you catch the ValueError before the test can receive it.
Remove the try catch and it should work
# mean_var_std.py
def calculate(list):
if len(list) < 9:
print("List must contain nine numbers.")
raise ValueError
else:
return 0

os.environ raises keyerror(key) from none

I am making a database gui program and I am experimenting on how to make the .db file in a different folder from the script. I am using python 3.7. Here is the function that I use:
def get_database_file():
dir_path = os.path.join(os.environ[''], 'test_database')
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_path = os.path.join(dir_path, 'test_database.db')
if not os.path.exists(file_path):
try:
conn = sqlite3.connect(file_path)
conn.execute("PRAGMA foreign_keys = 1")
except sqlite3.Error as err:
if conn:
conn.rollback() # reverse any changes before the commit
print("SQLite Error: %s" % err.args[0])
sys.exit(-1)
else:
createDatabase(file_path)
print("Finish database created")
finally:
if conn:
conn.close()
else:
return file_path
if os.stat(file_path) == 0:
print("Empty")
else:
print("Not Empty")
return file_path
When I put os.environ['APPDATA'], this function runs fine without any errors. But when I put os.environ['HOME'], it shows this error message:
Traceback (most recent call last):
File "C:/Users/jojot/PycharmProjects/CreateDatabase/gui_database.py", line 4214, in <module>
database_file = get_database_file()
File "C:/Users/jojot/PycharmProjects/CreateDatabase/gui_database.py", line 4178, in get_database_file
dir_path = os.path.join(os.environ['HOME'], 'test_database')
File "C:\Users\jojot\AppData\Local\Programs\Python\Python37-32\lib\os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'HOME'
I don't understand, what did I do wrong? Please help. Thank you.
It means that you haven't set the environment variable HOME.
If you want the program not to crash if you haven't set that variable you can use:
x = os.environ.get('HOME')
print(x) # None
instead of:
x = os.environ['HOME']
# raise KeyError(key) from None
# KeyError: 'HOME'

problem with UnboundLocalError: local variable referenced before assignment

So I'm testing my knowledge on webscraping by writing this little script (I know some things are redundant, it's just me playing around with things):
def programstart():
import re
from selenium import webdriver
from bs4 import BeautifulSoup
ff=webdriver.Firefox()
ff.get('https://www.ozbargain.com.au/deals')
linkpattern = r'https://www.ozbargain.com.au/node/.*'
donotpassthislink = 'https://www.ozbargain.com.au/node/415763'
#list of found lnks
titlelist = []
#loop to find links
while True:
soup = BeautifulSoup(ff.page_source)
raw_links = soup.find_all(name='a', href=re.compile(linkpattern))
for links in raw_links:
titles = ff.find_element_by_xpath("//h2[#class='title']").text
extract = links
if donotpassthislink == extract:
break
else:
pass
titlelist.append(titles)
# Load next page
if donotpassthislink == extract: # stop loop at first movie link from last time.
break
else:
ff.get(ff.find_element_by_xpath("//a[#class='pager-next active']").get_attribute('href'))
programstart()
I get this error:
Traceback (most recent call last):
File "F:/Dropbox/Funfile/ben.py", line 35, in <module>
programstart()
File "F:/Dropbox/Funfile/ben.py", line 29, in programstart
if donotpassthislink == extract: # stop loop at first movie link from last time.
UnboundLocalError: local variable 'extract' referenced before assignment
I find this weird since this loop was used in another script that works perfectly.
So I write a simplified script:
test = 'lets break this sentence up'
list = []
def func():
while True:
for i in test:
extract = i
print(extract)
if extract == 'u':
break
else:
pass
list.append(extract)
if extract == 'u':
print('done')
break
func()
And it executes without any issues.
What's going on?

Having trouble with Built-in Exception: ModuleNotFoundError

Having trouble with Built-in Exception: ModuleNotFoundError. I see nothing wrong with this solution, but am getting an Error. Checked out the docs but couldn't figure it out
folder structure
app
__init__.py
logic.py
test
__init__.py
test_logic.py
this error comes when i try to run the file from the command line directly --python test/test_logic.py
(tdd) D:\code\Outcome-15>coverage run test/test_logic.py
Traceback (most recent call last):
File "test/test_logic.py", line 3, in <module>
from app.logic import FizzBuzz
ModuleNotFoundError: No module named 'app'
logic.py
class FizzBuzz:
def fizz_buzz_service(self, num):
number_types = (int, float, complex)
if isinstance(num, number_types):
if num % 5 == 0 and num % 3 == 0:
return 'FizzBuzz'
elif num % 5 == 0:
return 'Buzz'
elif num % 3 == 0:
return 'Fizz'
else:
return num
else:
raise ValueError
test_logic.py
import unittest
from app.logic import FizzBuzz
class FizzBuzzServiceTestCases(unittest.TestCase):
"""
docstring for FizzBuzzServiceTestCases goes here!
"""
def setUp(self):
"""
Create an instance of fizz_buzz_service
"""
self.fizzbuzz = FizzBuzz()
def test_it_returns_a_number(self):
"""
Test for the default behavior of returning a number if not divisible by 3, 5 or both
"""
self.assertEqual(7, self.fizzbuzz.fizz_buzz_service(7))
def test_should_return_Fizz(self):
self.assertEqual("Fizz", self.fizzbuzz.fizz_buzz_service(3))
def test_should_return_Buzz(self):
self.assertEqual('Buzz', self.fizzbuzz.fizz_buzz_service(5))
def test_should_return_FizzBuzz(self):
self.assertEqual('FizzBuzz', self.fizzbuzz.fizz_buzz_service(15))
def test_should_return_error_message_if_arg_not_number(self):
with self.assertRaises(ValueError):
self.fizzbuzz.fizz_buzz_service('five')
if __name__ == '__main__':
unittest.main()

Python 3 - reading files, counting, and filtering text

I am working on a code in Python 3 with the following prompt:
Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence:0.8475. When you encounter a line that starts with X-DSPAM-Confidence: pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
I have started writing my code (below), but keep getting the following error message from Python:
Traceback (most recent call last):
File "spam_lines_in_file.py", line 14, in <module>
for line in fhand:
NameError: name 'fhand' is not defined
0587388179:ch_07_files juliecruz$
I'm confused because I have defined the variable 'fhand'. Any help from the experts?
count = 0
sum = 0
user = input('Please enter a file name')
try:
fhand = open(user)
except:
print("Not a valid file")
for line in fhand:
line = line.rstrip()
if line.startswith('X-DSPAM-Confidence:'):
print(lines)
count += 1
colon_position = int(line.find(":"))
extract = line[colon_position+1:]
number_extract = float(extract)
sum += number_extract
print("Extracted lines", count)
print("Sum of confidence values", sum)
print("Average of confidence values", sum/count)
Your problem is that fhand is only assigned a value if no exceptions occur.
You wrote:
try:
fhand = open(user)
except:
print("Not a valid file")
So in the case of an exception, fhand is not assigned a value. Which means that when you try to iterate over it, Python throws a NameError as it was never defined.
Maybe what you want is to terminate in the case of an exception? For example:
import sys
try:
fhand = open(user)
except:
print("Not a valid file")
sys.exit()
Or assign a default value to fhand?
import sys
try:
fhand = open(user)
except:
print("Not a valid file")
fhand = 'Default content'
The most likely reason is that, if a error occurs during opening the file, then a warning message is shown "Not a valid file", but processing then continues.
In that case fhand would not be assigned a value, and there would be a NameError
You probably want a loop that repeatedly asks for a filename, and only breaks out when the file has been opened successfully.
while True:
name = input("filename ... ")
try:
fhand = open(name)
except OSerror: # only catch OS errors, not everything.
print("not a valid file")
else:
break
fhand is a file object
try:
fhand = open(user)
except:
print("Not a valid file")
You can not do the following on a file object.
for line in fhand:
You would need to do this:
for line in fhand.readlines():
This isn't a problem for you yet, but it will be soon.
Your real problem is this:
When this code
try:
fhand = open(user)
throws an exception, the fhand variable doesn't get created, so you'd need to exit in the except block.
try:
fhand = open(user)
except:
print("Not a valid file")
sys.exit(1)
There is a mistake in line 11 :) - change to "line"
print(lines)

Resources