Python For Loop errors on sedond Pass - python

I am trying to use a for loop as follows:
addresses = [0x30, 0x31, 0x32, 0x33]
for address in addresses:
print(address)
chirp = chirp.Chirp(address=address,
read_moist=True,
read_temp=True,
read_light=True,
min_moist=False,
max_moist=False,
temp_scale='farenheit',
temp_offset=0)
chirp.trigger()
log_values(address, chirp.moist, chirp.temp, chirp.light)
time.sleep(1)
It seems to work on the first pass in the console I see 48, then 49 then get this error:
Traceback (most recent call last):
File "readings_logger.py", line 17, in <module>
chirp = chirp.Chirp(address=address,
AttributeError: 'Chirp' object has no attribute 'Chirp'
Which I think indicates that it ran once. Then on the second pass could not run it. My first thought was a local variable issue so tried to delete 'chirp' lower case 'c' but that did not help. My guess is this threading but I am new to python and not sure how to prevent that.

You are reassigning chirp when you are setting it equal to chirp.Chirp(...).
Try to change the variable assignment (after print(address) to something like loop_chirp = chirp.Chirp(...). Each subsequent line would now be changed to loop_chirp followed by the attribute.

Related

I have a Name error in python 3, it is with the variable "userMessage"

#Start
def main():
#variables
encryptedMessage=""
userMessage = input("you're message here: ")
shift=5
#for loop
for character in userMessage:
#5:50AM February 24th, 2020
eN = ord(character)
eN+= shift
encryptedMessage += chr(eN)
main()
print(userMessage)
print(encrytedMessage)
I have been in python a year now and never got this error mainly because I don't use for loops. when I use userMessage in print or for the for loop there's an error. I have tried resolving this using global, but it did not work so I simply removed it.
Traceback (most recent call last):
File "C:/Users/Eshan/Downloads/cypher.py", line 18, in <module>
print(userMessage)
NameError: name 'userMessage' is not defined
Since you are trying to print the value which is local variable, outside the function because of which you are getting "userMessage" not defined error.
You need to declare the variable as global and need to initiate it if you want to use it outside your function

print help text in try-exception in python

in a try-exception block in python, like shown below, I want my help message to be printed, instead of python's own error message. Is this possible?
def genpos(a):
''' Generate POSCAR :
Some error message'''
try:
tposcar = aio.read(os.path.join(root,"nPOSCAR"))
cell = (tposcar.get_cell())
cell[0][0] = a
cell[1][1] = math.sqrt(3)*float(a)
tposcar.set_cell(cell, scale_atoms=True)
aio.write("POSCAR", tposcar, direct=True)
except:
help(genpos)
sys.exit()
So, say, when this code is called without an argument, I want to get "Generate POSCAR : Some error message" instead of, python's
Traceback (most recent call last):
File "submit.py", line 41, in <module>
main()
File "submit.py", line 36, in __init__
ase_mod.genpos()
TypeError: genpos() missing 1 required positional argument: 'a'
You can define a new exception:
class CustomError(Exception): pass
raise CustomError('Generate POSCAR : Some error message')
Although, the error you're receiving has nothing to do with the try-except statement. Instead, your gen_pos() function is missing an argument.

How do I use python-WikEdDiff?

I recently installed python-WikEdDiff package to my system. I understand it is a python extension of the original JavaScript WikEdDiff tool. I tried to use it but I couldn't find any documentation for it. I am stuck at using WikEdDiff.diff(). I wish to use the other functions of this class, such as getFragments() and others, but on checking, it shows the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/WikEdDiff/diff.py", line 1123, in detectBlocks
self.getSameBlocks()
File "/usr/local/lib/python3.4/dist-packages/WikEdDiff/diff.py", line 1211, in getSameBlocks
while j is not None and self.oldText.tokens[j].link is None:
IndexError: list index out of range
On checking, I found out that the tokens[] structure in the object remains empty whereas it should have been initialized.
Is there an initialize function that I need to call apart from the default constructor? Or is it something to do with the `WikEdDiffConfig' config structure I passed to the constructor?
You get this error because the WikEdDiff object was cleared internally inside diff(), as shown in this section of the code:
def diff( self, oldString, newString ):
...
# Free memory
self.newText.tokens.clear()
self.oldText.tokens.clear()
# Assemble blocks into fragment table
fragments = self.getDiffFragments()
# Free memory
self.blocks.clear()
self.groups.clear()
self.sections.clear()
...
return fragments
If you just need the fragments, use the returned variable of diff() like this:
import WikEdDiff as WED
config=WED.WikEdDiffConfig()
w = WED.WikEdDiff(config)
f = w.diff("abc", "efg")
# do whatever you want with f, but don't use w
print(' '.join([i.text+i.type for i in f]))
# outputs '{ [ (> abc- ) abc< efg+ ] }'

TypeError: in Python

I have an issue, where a function returns a number. When I then try to assemble a URL that includes that number I am met with failure.
Specifically the error I get is
TypeError: cannot concatenate 'str' and 'NoneType' objects
Not sure where to go from here.
Here is the relevant piece of code:
# Get the raw ID number of the current configuration
configurationID = generate_configurationID()
# Update config name at in Cloud
updateConfigLog = open(logBase+'change_config_name_log.xml', 'w')
# Redirect stdout to file
sys.stdout = updateConfigLog
rest.rest(('put', baseURL+'configurations/'+configurationID+'?name=this_is_a_test_', user, token))
sys.stdout = sys.__stdout__
It works perfectly if I manually type the following into rest.rest()
rest.rest(('put', http://myurl.com/configurations/123456?name=this_is_a_test_, myusername, mypassword))
I have tried str(configurationID) and it spits back a number, but I no longer get the rest of the URL...
Ideas? Help?
OK... In an attempt to show my baseURL and my configurationID here is what I did.
print 'baseURL: '+baseURL
print 'configurationID: '+configurationID
and here is what I got back
it-tone:trunk USER$ ./skynet.py fresh
baseURL: https://myurl.com/
369596
Traceback (most recent call last):
File "./skynet.py", line 173, in <module>
main()
File "./skynet.py", line 30, in main
fresh()
File "./skynet.py", line 162, in fresh
updateConfiguration()
File "./skynet.py", line 78, in updateConfiguration
print 'configurationID: '+configurationID
TypeError: cannot concatenate 'str' and 'NoneType' objects
it-tone:trunk USER$
What is interesting to me is that the 369596 is the config ID, but like before it seems to clobber everything called up around it.
As kindall pointed out below, my generate_configurationID was not returning the value, but rather it was printing it.
# from generate_configurationID
def generate_configurationID():
dom = parse(logBase+'provision_template_log.xml')
name = dom.getElementsByTagName('id')
p = name[0].firstChild.nodeValue
print p
return p
Your configurationID is None. This likely means that generate_configurationID() is not returning a value. There is no way in Python for a variable name to "lose" its value. The only way, in the code you posted, for configurationID to be None is for generate_configurationID() to return None which is what will happen if you don't explicitly return any value.
"But it prints the configurationID right on the screen!" you may object. Sure, but that's probably in generate_configurationID() where you are printing it to make sure it's right but forgetting to return it.
You may prove me wrong by posting generate_configurationID() in its entirety, and I will admit that your program is magic.

Python: TypeError: 'float' object is not callable

I am trying to join 2 strings using this code:
def __get_temp(self):
return float(self.ask('RS'))
def __set_temp(self, temp):
set = ('SS' + repr(temp))
stat = self.ask(set)
return self.check(stat)
temp = property(__get_temp, __set_temp)
Once together, I then send a signal over a serial bus using PyVisa. However, when I try to call the function, I get
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
chil.temp(13)
TypeError: 'float' object is not callable
I've tried looking around for explanation of this error, but none of them make any sense. Anyone know what is going on?
It looks like you are trying to set the property temp, but what you're actually doing is getting the property and then trying to call it as function with the parameter 13. The syntax for setting is:
chil.temp = 13

Categories