micropython: loading data from a file in function causing an endless loop - micropython

I am working on a lopy4 from pycom and I have encountered an od problem while loading config data from a txt file:
def loadFromConfigFile():
f= open('config.txt')
for line in f:
if "uuidExpected" in line:
uuidExpected=line[13:len(line)-1].strip()
elif "app_eui" in line:
app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "app_key" in line:
app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "syncClockTime" in line:
syncClockTime=float(line[14:len(line)-1].strip())
elif "loraJoinTime" in line:
loraJoinTime=float(line[13:len(line)-1].strip())
elif "bleScanInterval" in line:
bleScanInterval=int(line[16:len(line)-1].strip())
elif "mainLoopWaitTime" in line:
mainLoopWaitTime=int(line[17:len(line)-1].strip())
elif "hbInterval" in line:
hbInterval=int(line[11:len(line)-1].strip())
f.close()
loadFromConfigFile()
When I use this function my programme gets stuck here:
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
while not lora.has_joined():
time.sleep(loraJoinTime)
print('Not yet joined...')
print("joined!")
setClock()
The sleep function doesn't work and the print function spams "Not yet joined..." in the terminal window.
f= open('config.txt')
for line in f:
if "uuidExpected" in line:
uuidExpected=line[13:len(line)-1].strip()
elif "app_eui" in line:
app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "app_key" in line:
app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "syncClockTime" in line:
syncClockTime=float(line[14:len(line)-1].strip())
elif "loraJoinTime" in line:
loraJoinTime=float(line[13:len(line)-1].strip())
elif "bleScanInterval" in line:
bleScanInterval=int(line[16:len(line)-1].strip())
elif "mainLoopWaitTime" in line:
mainLoopWaitTime=int(line[17:len(line)-1].strip())
elif "hbInterval" in line:
hbInterval=int(line[11:len(line)-1].strip())
f.close()
When I don't wrap this code into a function everything works. When I write the function after the hardcoded loop everything works as well.

Thanks, to nekomatics comment I solved the issue. I simply wasn't aware of the global keyword in python. To stay with the same logic as before, the code should look like this.
def loadFromConfigFile():
global uuidExpected
global app_eui
global syncClockTime
global loraJoinTime
global bleScanInterval
global mainLoopWaitTime
global hbInterval
f= open('config.txt')
for line in f:
if "uuidExpected" in line:
uuidExpected=line[13:len(line)-1].strip()
elif "app_eui" in line:
app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "app_key" in line:
app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "syncClockTime" in line:
syncClockTime=float(line[14:len(line)-1].strip())
elif "loraJoinTime" in line:
loraJoinTime=float(line[13:len(line)-1].strip())
elif "bleScanInterval" in line:
bleScanInterval=int(line[16:len(line)-1].strip())
elif "mainLoopWaitTime" in line:
mainLoopWaitTime=int(line[17:len(line)-1].strip())
elif "hbInterval" in line:
hbInterval=int(line[11:len(line)-1].strip())
f.close()

Related

How Do I Solve: [ValueError: invalid literal for int() with base 10:]

command= " "
while True:
command = int(input("how old are you? "))
if command <= 12:
print("you're ticket is free.")
elif command <= 15:
print("you're ticket is $20.")
elif command > 15:
print("you're ticket is $50.")
elif command == "exit":
break
As I write exit it gives a ValueError,
ValueError: invalid literal for int() with base 10:'exit'
You should check if the command is exit before trying to convert the command to int:
while True:
command = input("how old are you? ")
if command == "exit":
break
command = int(command)
if command <= 12:
print("you're ticket is free.")
elif command <= 15:
print("you're ticket is $20.")
elif command > 15:
print("you're ticket is $50.")

Python 3.7.3 variables with numbers in while loop conditionals

So I'm trying to learn some python3 with some simple code as stated below. The point of the code is to have a loop that runs until one of the files exists and contains data. For some reason i'm getting an error running this, saying that the variable has an invalid syntax just as if numbers in variables are illegal (which they arent?):
$ python3 test.py
File "test.py", line 14
While file1==False and file2==False and file3==False:
^
SyntaxError: invalid syntax
Code:
import os
filePath1 = '/some/path'
filePath2 = '/some/path'
filePath3 = '/some/path'
file1 = False
file2 = False
file3 = False
While file1==False and file2==False and file3==False:
if os.path.exists(filePath1):
with open(filePath1,'r') as f:
try:
file1 = f.read()
except:
print("No file data.")
if os.path.exists(filePath2):
with open(filePath2,'r') as f:
try:
file2 = f.read()
except:
print("No file data.")
if os.path.exists(filePath3):
with open(filePath3,'r') as f:
try:
file3 = f.read()
except:
print("No file data.")
I don't understand this because:
>>>file1=False
>>>file2=False
>>>file1==False and file2==False
True
I'd be grateful for any help
invalid syntax is caused by your capitalized While keyword, which python doesn't recognize. Use the reserved keyword while, small letters only.

ERROR: YoctoProject - core-image-sato: do_populate_sdk

I am a beginner in Yocto project. I am trying to build the image for Beaglebone Black Board with command-line: bitbake core-image-sato -c populate_sdk and I had an error (the detail in the below) in last task.
Enviroment build: Ubuntu 16.04 LTS, using Bash Shell instead of Dash Shell.
I tried to build again many times but still facing same error. Anybody can help me to fix this error?
Log file:
NOTE: Executing create_sdk_files ...
DEBUG: Executing shell function create_sdk_files
DEBUG: Shell function create_sdk_files finished
NOTE: Executing check_sdk_sysroots ...
DEBUG: Executing python function check_sdk_sysroots
DEBUG: Python function check_sdk_sysroots finished
NOTE: Executing archive_sdk ...
DEBUG: Executing shell function archive_sdk
/home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/temp/run.archive_sdk.4392: line 106: 11617 Broken pipe tar --owner=root --group=root -cf - .
11618 Killed | xz -T 0 -9 > /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/x86_64-deploy-core-image-sato-populate-sdk/poky-glibc-x86_64-core-image-sato-armv7at2hf-neon-beaglebone-toolchain-3.0.tar.xz
WARNING: /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/temp/run.archive_sdk.4392:1 exit 137 from 'xz -T 0 -9 > /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/x86_64-deploy-core-image-sato-populate-sdk/poky-glibc-x86_64-core-image-sato-armv7at2hf-neon-beaglebone-toolchain-3.0.tar.xz'
ERROR: Error executing a python function in exec_python_func() autogenerated:
The stack trace of python calls that resulted in this exception/failure was:
File: 'exec_python_func() autogenerated', lineno: 2, function: <module>
0001:
*** 0002:do_populate_sdk(d)
0003:
File: '/home/huongnguyen/Desktop/poky/openembedded-core/meta/classes/populate_sdk_base.bbclass', lineno: 169, function: do_populate_sdk
0165:
0166: populate_sdk(d)
0167:
0168:fakeroot python do_populate_sdk() {
*** 0169: populate_sdk_common(d)
0170:}
0171:SSTATETASKS += "do_populate_sdk"
0172:SSTATE_SKIP_CREATION_task-populate-sdk = '1'
0173:do_populate_sdk[cleandirs] = "${SDKDEPLOYDIR}"
File: '/home/huongnguyen/Desktop/poky/openembedded-core/meta/classes/populate_sdk_base.bbclass', lineno: 166, function: populate_sdk_common
0162: manifest_type=Manifest.MANIFEST_TYPE_SDK_HOST)
0163: create_manifest(d, manifest_dir=d.getVar('SDK_DIR'),
0164: manifest_type=Manifest.MANIFEST_TYPE_SDK_TARGET)
0165:
*** 0166: populate_sdk(d)
0167:
0168:fakeroot python do_populate_sdk() {
0169: populate_sdk_common(d)
0170:}
File: '/home/huongnguyen/Desktop/poky/openembedded-core/meta/lib/oe/sdk.py', lineno: 413, function: populate_sdk
0409: env_bkp = os.environ.copy()
0410:
0411: img_type = d.getVar('IMAGE_PKGTYPE')
0412: if img_type == "rpm":
*** 0413: RpmSdk(d, manifest_dir).populate()
0414: elif img_type == "ipk":
0415: OpkgSdk(d, manifest_dir).populate()
0416: elif img_type == "deb":
0417: DpkgSdk(d, manifest_dir).populate()
File: '/home/huongnguyen/Desktop/poky/openembedded-core/meta/lib/oe/sdk.py', lineno: 60, function: populate
0056: self.sysconfdir, "ld.so.cache")
0057: self.mkdirhier(os.path.dirname(link_name))
0058: os.symlink("/etc/ld.so.cache", link_name)
0059:
*** 0060: execute_pre_post_process(self.d, self.d.getVar('SDK_POSTPROCESS_COMMAND'))
0061:
0062: def movefile(self, sourcefile, destdir):
0063: try:
0064: # FIXME: this check of movefile's return code to None should be
File: '/home/huongnguyen/Desktop/poky/openembedded-core/meta/lib/oe/utils.py', lineno: 260, function: execute_pre_post_process
0256: for cmd in cmds.strip().split(';'):
0257: cmd = cmd.strip()
0258: if cmd != '':
0259: bb.note("Executing %s ..." % cmd)
*** 0260: bb.build.exec_func(cmd, d)
0261:
0262:# For each item in items, call the function 'target' with item as the first
0263:# argument, extraargs as the other arguments and handle any exceptions in the
0264:# parent thread
File: '/home/huongnguyen/Desktop/poky/bitbake/lib/bb/build.py', lineno: 249, function: exec_func
0245: with bb.utils.fileslocked(lockfiles):
0246: if ispython:
0247: exec_func_python(func, d, runfile, cwd=adir)
0248: else:
*** 0249: exec_func_shell(func, d, runfile, cwd=adir)
0250:
0251: try:
0252: curcwd = os.getcwd()
0253: except:
File: '/usr/lib/python3.5/contextlib.py', lineno: 77, function: __exit__
0073: # Need to force instantiation so we can reliably
0074: # tell if we get the same exception back
0075: value = type()
0076: try:
*** 0077: self.gen.throw(type, value, traceback)
0078: raise RuntimeError("generator didn't stop after throw()")
0079: except StopIteration as exc:
0080: # Suppress StopIteration *unless* it's the same exception that
0081: # was passed to throw(). This prevents a StopIteration
File: '/home/huongnguyen/Desktop/poky/bitbake/lib/bb/utils.py', lineno: 431, function: fileslocked
0427: if files:
0428: for lockfile in files:
0429: locks.append(bb.utils.lockfile(lockfile))
0430:
*** 0431: yield
0432:
0433: for lock in locks:
0434: bb.utils.unlockfile(lock)
0435:
File: '/home/huongnguyen/Desktop/poky/bitbake/lib/bb/build.py', lineno: 249, function: exec_func
0245: with bb.utils.fileslocked(lockfiles):
0246: if ispython:
0247: exec_func_python(func, d, runfile, cwd=adir)
0248: else:
*** 0249: exec_func_shell(func, d, runfile, cwd=adir)
0250:
0251: try:
0252: curcwd = os.getcwd()
0253: except:
File: '/home/huongnguyen/Desktop/poky/bitbake/lib/bb/build.py', lineno: 450, function: exec_func_shell
0446: with open(fifopath, 'r+b', buffering=0) as fifo:
0447: try:
0448: bb.debug(2, "Executing shell function %s" % func)
0449: with open(os.devnull, 'r+') as stdin, logfile:
*** 0450: bb.process.run(cmd, shell=False, stdin=stdin, log=logfile, extrafiles=[(fifo,readfifo)])
0451: finally:
0452: os.unlink(fifopath)
0453:
0454: bb.debug(2, "Shell function %s finished" % func)
File: '/home/huongnguyen/Desktop/poky/bitbake/lib/bb/process.py', lineno: 182, function: run
0178: if not stderr is None:
0179: stderr = stderr.decode("utf-8")
0180:
0181: if pipe.returncode != 0:
*** 0182: raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
0183: return stdout, stderr
Exception: bb.process.ExecutionError: Execution of '/home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/temp/run.archive_sdk.4392' failed with exit code 137:
/home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/temp/run.archive_sdk.4392: line 106: 11617 Broken pipe tar --owner=root --group=root -cf - .
11618 Killed | xz -T 0 -9 > /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/x86_64-deploy-core-image-sato-populate-sdk/poky-glibc-x86_64-core-image-sato-armv7at2hf-neon-beaglebone-toolchain-3.0.tar.xz
WARNING: /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/temp/run.archive_sdk.4392:1 exit 137 from 'xz -T 0 -9 > /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/x86_64-deploy-core-image-sato-populate-sdk/poky-glibc-x86_64-core-image-sato-armv7at2hf-neon-beaglebone-toolchain-3.0.tar.xz'
ERROR: Logfile of failure stored in: /home/huongnguyen/Desktop/poky/build/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/temp/log.do_populate_sdk.4392
ERROR: Task (/home/huongnguyen/Desktop/poky/openembedded-core/meta/recipes-sato/images/core-image-sato.bb:do_populate_sdk) failed with exit code '1'
Exit code 137 means something killed xz during the build. You may be running out of memory: check dmesg after this happens, there might be a log line about out-of-memory killer.
Had the same problem and could make it go away with XZ_MEMLIMIT="75%" bitbake image-name -c do_populate_sdk. The bitbake.conf in my version of Yocto defaults XZ_MEMLIMIT to 50%.
Had the same problem and none of the usual methods, like, deleting hidden repo file worked.
I then clean the build using bitbake -c clean mybuildname and then again made the build and it worked flawlessly, I hope it helps someone.

Errors that I don't understand

I am trying to write a code from the following tutorial:
https://www.youtube.com/watch?v=9mAmZIRfJBs&t=197s
In my opinion I completely wrote it the same way, but it still gives an error. Can someone explain to me why Spyder(Python 3.7) does this.
This is my code:
I tried using another input function so raw_input instead of input. I also tried changing my working directory and saving the document
This is my code:
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 14:47:27 2019
#author: johan
"""
import random
restaurantsList = ['boloco', 'clover', 'sweetgreens']
def pickRestaurant():
print(restaurantsList[random.randint(0,2)])
def addRestaurant(name):
restaurantsList.append(name)
def removeRestaurant(name):
restaurantsList.remove(name)
def listRestaurant():
for restaurant in restaurantsList:
print(restaurant)
while True:
print('''
[1] - List restaurant
[2] - Add restaurant
[3] - Remove restaurant
[4] - Pick restaurant
[5] - Exit
''')
selection = raw_input(prompt='Please select an option: ')
if selection == '1':
print('')
listRestaurant()
elif selection == '2':
inName = raw_input(prompt='Type name of the restaurant that you want to add: ')
addRestaurant(inName)
elif selection == '3':
inName = raw_input(prompt='Type name of the restaurant that you want to remove: ')
removeRestaurant(inName)
elif selection == '4':
pickRestaurant()
elif selection == '5':
break
and this is the error
runfile('C:/Users/johan/Desktop/Unie jaar 2/untitled2.py', wdir='C:/Users/johan/Desktop/Unie jaar 2')
Traceback (most recent call last):
File "C:\Users\johan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-93-2d7193d6cafb>", line 1, in <module>
runfile('C:/Users/johan/Desktop/Unie jaar 2/untitled2.py', wdir='C:/Users/johan/Desktop/Unie jaar 2')
File "C:\Users\johan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\Users\johan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/johan/Desktop/Unie jaar 2/untitled2.py", line 35
selection = raw_input(prompt='Please select an option: ')
^
IndentationError: unindent does not match any outer indentation level
The code should give a list of restaurant is 1 is put in. You are able to add a restaurant to the list if 2 is put in. 3 is like to but then you remove. 4 picks a random restaurant from the list. 5 does nothing.
It's imperative that you indent correctly in Python, as such;
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 14:47:27 2019
#author: johan
"""
import random
restaurantsList = ['boloco', 'clover', 'sweetgreens']
def pickRestaurant():
print(restaurantsList[random.randint(0,2)])
def addRestaurant(name):
restaurantsList.append(name)
def removeRestaurant(name):
restaurantsList.remove(name)
def listRestaurant():
for restaurant in restaurantsList:
print(restaurant)
while True:
print('''
[1] - List restaurant
[2] - Add restaurant
[3] - Remove restaurant
[4] - Pick restaurant
[5] - Exit
''')
selection = input('Please select an option: ')
if selection == '1':
print('')
listRestaurant()
elif selection == '2':
inName = input('Type name of the restaurant that you want to add: ')
addRestaurant(inName)
elif selection == '3':
inName = input('Type name of the restaurant that you want to remove: ')
removeRestaurant(inName)
elif selection == '4':
pickRestaurant()
elif selection == '5':
break
Python is indentation sensitive, and when creating a function or any statements you need to indent any code inside that function or you will get the error you have above.
Additional note: You're using print() which is python2 and raw_input which is python3, so I've assumed Python3 and changed the raw_input() for input().
You have 4 spaces before print statement within while loop, but all other lines in that loop have 3 spaces indent only, starting from selection = raw_input...
You should add a space at the start for every line starting from selection = raw_input... and below.

IPython - Raise exception when a shell command fails

I'm using IPython as a system shell.
Is there a way to make IPython to raise an exception when the shell command fails? (non-zero exit codes)
The default makes them fail silently.
As of IPython 4.0.1, !cmd is transformed into get_ipython().system(repr(cmd)) (IPython.core.inputtransformer._tr_system()).
In the source, it's actually InteractiveShell.system_raw(), as inspect.getsourcefile() and inspect.getsource() can tell.
It delegates to os.system() in Windows and subprocess.call() in other OSes. Not configurable, as you can see from the code.
So, you need to replace it with something that would call subprocess.check_call().
Apart from monkey-patching by hand, this can be done with the IPython configuration system. Available options (viewable with the %config magic) don't allow to replace TerminalInteractiveShell with another class but several TerminalIPythonApp options allow to execute code on startup.
Do double-check whether you really need this though: a look through the system_raw()'s source reveals that it sets the _exit_code variable - so it doesn't actually fail completely silently.
If you use ! to execute shell commands, errors will pass silently
!echo "hello" && exit 1
hello
If you use the %%sh cell magic to execute the shell command, errors will raise:
%%sh
echo "hello" && exit 1
hello
---------------------------------------------------------------------------
CalledProcessError Traceback (most recent call last)
<ipython-input-10-9229f76cae28> in <module>
----> 1 get_ipython().run_cell_magic('sh', '', 'echo "hello" && exit 1\n')
~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2360 with self.builtin_trap:
2361 args = (magic_arg_s, cell)
-> 2362 result = fn(*args, **kwargs)
2363 return result
2364
~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/magics/script.py in named_script_magic(line, cell)
140 else:
141 line = script
--> 142 return self.shebang(line, cell)
143
144 # write a basic docstring:
<decorator-gen-110> in shebang(self, line, cell)
~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/anaconda/envs/altair-dev/lib/python3.6/site-packages/IPython/core/magics/script.py in shebang(self, line, cell)
243 sys.stderr.flush()
244 if args.raise_error and p.returncode!=0:
--> 245 raise CalledProcessError(p.returncode, cell, output=out, stderr=err)
246
247 def _run_script(self, p, cell, to_close):
CalledProcessError: Command 'b'echo "hello" && exit 1\n'' returned non-zero exit status 1.