Changing global variables and read them - python

I have properties file props.properties
[collect_data]
collect = True
And 2 files test2.py
import test1 as c
class Test:
def __init__(self):
pass
def printer(self):
print 'in test2 value is' c.COLLECT_DATA
And test1.py file with main function
from ConfigParser import ConfigParser
import test2 as t
DEFAULT_PROPS = '..//etc//props.properties'
COLLECT_DATA = False
class Initializer:
def __init__(self):
pass
def init_const(self, properties=DEFAULT_PROPS):
cfg = ConfigParser()
print 'Start'
cfg.read(properties)
global COLLECT_DATA = False
COLLECT_DATA = eval(cfg.get('collect_data', 'collect'))
print 'Now it is', COLLECT_DATA
if __name__ == '__main__':
i = Initializer()
i.init_const()
test = t.Test()
test.printer()
print COLLECT_DATA
I want to read properties from props file, assing it and read them in another file, but actually I have such logs:
Start
Now it True
in test2 value is False
True
How to solve it?

Related

How to call another class method that includes the other method?

I have a class below:
class Test:
def alpha(self):
a = 5
return a
def bravo(self):
alp = self.alpha()
c = 2
solution = alp + c
print(solution)
return solution
and I am trying to write a new class that calls Test.bravo(),
but having an error due to Test.alpha inside of it.
How can I write a new class? below is what I did:
class Test2:
def charlie(self):
call_bravo = Test.bravo(self)
print(call_bravo)
def main():
tst = Test()
tst.bravo()
tst2 = Test2()
tst2.charlie()
if __name__ == '__main__':
main()
The solution below works correctly.
class Test:
def alpha(self):
a = 5
return a
def bravo(self):
alp = self.alpha()
c = 2
solution = alp + c
print(solution)
class Test2:
def charlie(self):
call_bravo = Test()
res = call_bravo.bravo()
print(res)
def main():
tst = Test()
tst.bravo()
tst2 = Test2()
tst2.charlie()
if __name__ == '__main__':
main()
I expect that your error is because you're trying to invoke a method of class Test to operate on an object of Test2.
tst2.Charlie() invokes
Test.bravo(tst2), which invokes
tst2.alpha()
Your problem is that there is no such routine: the only alpha in your design is a method of Test; there is no alpha method for Test2.
In short, you have a fatal design error. Sort out what functionality you want in each class.

Dynamic variable from function in Python

var 1 is constantly changing with every new line that is written in the csv file. Any suggestion how can I get the value outside of the function. This example does not work for me.
I updated my code and added second function which is exactly the same but is reading another file. Now I only get print from the first function only. If I disable the first function I can get the print from the second function. Is there a way to print both of them or maybe three or four if I add later new functions ?
import sys
import time
import datetime
import os
class Application():
def loop_one(self):
filename = 'Test.csv'
mycsv = open(filename, 'r')
mycsv.seek(0, os.SEEK_END)
while 1:
time.sleep(1)
where = mycsv.tell()
line = mycsv.readline()
if not line:
mycsv.seek(where)
else:
arr_line = line.split(',')
var1 = arr_line[5]
mydate = datetime.datetime.now()
print var1, mydate.strftime("%H:%M:%S:%f")
return var1
def loop_two(self):
filename2 = 'Test2.csv'
mycsv2 = open(filename2, 'r')
mycsv2.seek(0, os.SEEK_END)
while 1:
time2.sleep(1)
where2 = mycsv2.tell()
line2 = mycsv2.readline()
if not line2:
mycsv2.seek(where2)
else:
arr_line2 = line2.split(',')
var2 = arr_line2[5]
mydate2 = datetime.datetime.now()
print var2, mydate.strftime("%H:%M:%S:%f")
return var2
s = Application()
var1 = s.loop_one()
var2 = s.loop_two()
You can declare a variable inside the init function so you can use that anywhere
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
In your case you can do something like this (not tested)
class Application():
def __init__(self):
self.filename = 'Test.csv'
self.mycsv = open(self.filename, 'r')
self.mycsv.seek(0, os.SEEK_END)
self.var1 = ''
def loop_one(self):
while 1:
time.sleep(1)
where = self.mycsv.tell()
line = self.mycsv.readline()
if not line:
self.mycsv.seek(where)
# you need a break here or somewhere :D
else:
arr_line = line.split(',')
self.var1 = arr_line[5]
mydate = datetime.datetime.now()
print self.var1, mydate.strftime("%H:%M:%S:%f")
return self.var1
s = Application()
s.loop_one()
You have move your if else block inside the for loop otherwise your code will stuck in infinite loop.
import sys
import time
import datetime
import os
class Application():
def loop_one(self):
filename = 'Test.csv'
mycsv = open(filename, 'r')
mycsv.seek(0, os.SEEK_END)
while 1:
time.sleep(1)
where = mycsv.tell()
line = mycsv.readline()
if not line:
mycsv.seek(where)
else:
arr_line = line.split(',')
var1 = arr_line[5]
mydate = datetime.datetime.now()
print var1, mydate.strftime("%H:%M:%S:%f")
return var1
s = Application()
s.loop_one()
Accessing var1 outside the function
class Application:
var1 = None
def loop_one(self):
# Code
while True:
# Your code
if not line:
# Code
else:
global var1
# Code
var1 = arr_line[5]
# Then you can access it via
def show():
print(var1)

Using variables from another module wih a while loop

main.py:
import sys
sys.path.append('Pygame Projects')
import sub
from sub import *
loop = True
while loop:
print_hello()
true_the_another_loop()
while anotherLoop:
print_world()
sub.py:
def true_the_another_loop():
loop = False
anotherLoop = True
def print_hello():
print "hello"
def print_world():
print "world"
When I run main.py, it prints only "hello". Why is "world" not being printed?
In true_the_another_loop(), the line loop = Flase does not seem to be working.
You need to return the new values of those variables. Because they were just local variables, they are limited to only that function. You need to pass their values to the other variables.
...
while loop:
print_hello()
loop, anotherLoop = true_the_another_loop()
...
def true_the_another_loop():
loop = False
anotherLoop = True
return [loop,anotherLop]

How to access a variable from a class of another module

I am a total python beginner and I have a variable created in a class of a file commandline_reader.py that I want to access from another script. I tried to do it by making the variable global, which doesn't work.
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
global output
output = []
def run(self):
# do stuff
a = 'somevariable'
output.append(a)
When I run myscript.py I always get a NameError: name 'output' is not defined. I've read that this is because global variables are only defined within a module. How do I correctly access the output variable in my script?
ouch. The whole reason object oriented programming takes place is to avoid the use of global variables. Make them instance variables to access them anywhere in the class.
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) #output is now part of the instance Commandline reader and can be accessed anywhere inside the class.
clr = Commandline_Reader(argstring='--get_serial_number')
clr.run()
print clr.output
>>>['somevariable']
Make output an instance attribute:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = [] # note use of self here
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) # and here
The access it via the instance:
print reader.output
Maybe class attribute is more appropriate for you?
class Commandline_Reader:
output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
Just return the Value from the run() Method
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
output = reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
return self.output

Class data attribute not being accessible in class method

I have written a small program that will print all the files and directories inside the path specified by me. The source code is:
import os
import glob
class FolderStats:
targetdir = ""
def __init__(self, dirpath = None):
targetdir = dirpath
totalfiles = 0
totalsubfolders = 0
def FolderIterator(self):
print self.targetdir
listing = os.listdir(self.targetdir)
for infile in listing:
print "current file is: %s" % (infile)
if __name__ == '__main__':
Obj = FolderStats(raw_input('Enter your path: '))
Obj.FolderIterator()
The above code is not executing. I am getting an error in the method FolderIterator: when the print command is executed, it prints nothing. <targetdir> no more contains the path supplied by me. Why is it so?
In your __init__ you need to use self.targetdir instead of targetdir
>>> class Test:
var = 1
def __init__(self):
var = 2
print self.var # Object variable
print var # Local variable
def func(self):
print self.var
print var # this will fail, because there's no local var in this scope
>>> a = Test()
1
2
>>> a.func()
1
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a.func()
File "<pyshell#10>", line 9, in func
print var
NameError: global name 'var' is not defined

Categories

Resources