Python-Firebase printing multiple times - python

This is a script using python-firebase:
from firebase import firebase
firebase = firebase.FirebaseApplication('https://<my-firebase-id>.firebaseio.com', None)
result = firebase.get('/status/time', None)
print result
Everything works as intended (displaying the word "time"), except that it prints it in 6 different lines, like so:
time
time
time
time
time
time
[Finished in 3.3s]
Why does this occur?

I compiled with Python 3.4 instead of Python 2.7 as I was previously using, solving my problem.

Related

Could anyone give a simple but generally useful template for python code to be embedded into LibreOffice Calc?

Update acknowledging comment 1 and 4:
Indentation corrected, does compile in Geany, obvious redundancies stripped.
The first question is: why am I getting the args error when I try to run my code? The error message refers to a LO file.... (linux) /opt/libreoffice7.2/programs/pythonscript.py # line 915.
An excerpt from that file says...
def invoke(self, args, out, outindex ): # 910
log.debug( "PythonScript.invoke " + str( args ) ) # 911
try: # 912
if (self.args): # 913
args += self.args # 915
ret = self.func( *args ) # 915
My code is...
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
# Gets the current document
doc = XSCRIPTCONTEXT.getDocument()
ctx = XSCRIPTCONTEXT.getComponentContext()
sm = CTX.ServiceManager
import time
import datetime
import serial
import openpyxl
def PySerLO (args=None):
from datetime import date
from openpyxl import load_workbook
ser = serial.Serial('/dev/ttyUSB0') # ""ls /dev/ttyUSB* -l"" if unsure.
# Load the workbook and select the sheet...
wb = load_workbook('/media/mpa/UserFiles/LibreOffice/mpaNEW-spreadsheet.xlsx')
sheet = wb['Sheet1']
headings = ("Date", "Time", "Raw Data")
sheet.append(headings)
try:
while True:
# Get current date, Get current time, Read the serial port
today = date.today()
now = datetime.datetime.now().time()
data = ser.readline().decode()
if data != "":
row = (today, now, float((data))) # For some reason the first data point is garbage so don't do anything with this
row = (today, ("%s"%now), float((data)))
sheet.append(row)
ser.flush()
#Save the workbook to preserve data
wb.save('/media/mpa/UserFiles/LibreOffice/mpaNEW-spreadsheet.xlsx')
finally:
# Make sure the workbook is saved at end
wb.save('/media/mpa/UserFiles/LibreOffice/mpaNEW-spreadsheet.xlsx')
print('Data Finished')
I get this error on executing a macro executing command button...
I appreciate your patience and suggestions on improvement thus far.
The ultimate aim of this is to track and instantly plot scientific data, introduce my students to the power of LibreOffice - They download LO and I just pass them the fully contained spreadsheet. They then connect the hardware and they have an excellent resource on LO forever. Almost none of them have ever heard of LibreOffice (or Linux either!)
First of all, I do not think you should start by embedding the macro in the document. I don't think it is required for the reasons you seem to believe. Instead, put your code in My Macros (the LibreOffice user directory) where it is easier to develop. Then call it from a button or by going to Tools > Macros > Run Macro - no need to use APSO as it seems like that is causing you even more confusion. The only reason for embedding is for convenience, to make it easier to keep the document and a bit of code together. For complex code that needs to be given to multiple people, it's generally better to create a full-fledged extension.
Second, it looks like the error may be from M1.py line 22 - is this your code? I cannot tell where line 22 might be or where exactly the error is coming from. Most of us reading your question are looking for the code where the error message comes from, but we cannot find it because you did not provide the relevant file name or line number of your code. It is your job to simplify your code enough so that you can see where the error is coming from, and then give that information in the question.
The error mentions create_instance which is the call for creating an UNO service.
Also I am not comfortable with the idea of storing XSCRIPTCONTEXT values in global variables unless you're sure you know what you're doing (and it's pretty clear you don't. :) )
Also I have strong doubts about achieving success by combining different libraries - it looks like you want to use both openpyxl and the UNO interface in the same code, and I would not expect that to turn out well. Just stick with plain UNO because there are plenty of people who can help with that. (Or if you choose openpyxl then I will ignore your question and someone knowledgeable about that may be able to help.)
Finally, it seems like import uno is missing. That alone could explain the error, and it's hard to imagine how you have all this code yet didn't even start with that.
Before trying all of this complex code, get a simple example working. It looks like there are a lot of python-uno fundamentals you still need to figure out first, and it doesn't look like you have put much effort into working through a tutorial yet.

Python 2.7 Yahoo Finance No Definition Found

Hope you are well. I'm Using Python 2.7 and new at it. I'm trying to use yahoo finance API to get information from stocks, here is my code:
from yahoo_finance import Share
yahoo = Share('YHOO')
print yahoo.get_historical('2014-04-25', '2014-04-29')
This code thoug works once out of 4 attempts, the other 3 times gives me this errors:
YQL Query error: Query failed with error: No Definition found for Table yahoo.finance.quote
Is there anyway to fix this error so to have the code working 100% of the time?
Thanks.
Warmest regards
This is a server-side error. The query.yahooapis.com service appears to be handled by a cluster of machines, and some of those machines appear to be misconfigured. This could be a temporary problem.
I see the same error when accessing the API directly using curl:
$ curl "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20%3D%20%22YHOO%22&format=json&env=store%3a//datatables.org/alltableswithkeys"
{"error":{"lang":"en-US","description":"No definition found for Table yahoo.finance.quote"}}
Other than retrying in a loop, there is no way to fix this on the Python side:
data = None
for i in range(10): # retry 10 times
try:
yahoo = Share('YHOO')
data = yahoo.get_historical('2014-04-25', '2014-04-29')
break
except yahoo_finance.YQLQueryError:
continue
if data is None:
print 'Failed to retrieve data from the Yahoo service, try again later'

Convert a String To Integer From File Located on SD Card

I am having a problem converting strings to integers so I can perform math functions. I have read about str() and int() but it doesn't seem to work here. I am trying to save data from one program to a file located on my Raspberry Pi 2 SD card using the code shown below; problem area is noted in CAPS near the bottom. I learned all data getting saved to the file are in string format. So no problem, just convert it back to an integer when I get the following error message:
ValueError: invalid literal for int() with base 10
I tried Python versions 2 and 3 on my Raspberry Pi 2. The reason for this is that I have a counter in my main program that I want to update with its last position in the event of loss of power to the Raspberry Pi.
I have been pulling my hair out on this. Can someone please help me find the answer. I have been unable to find it myself on the internet, or in two Python books I purchased.
from __future__ import print_function
import datetime #date and time library
# We begin by creating the file and writing some data.
webcam_home = open("home.txt", "a")
n = 1
m = 10
for i in range(0,5):
n = n*10
m = m*2
webcam_home.write(str(n))
webcam_home.write("%s\n" % m)
webcam_home.close()
# Now, we open the file and read the contents printing out
# those rows that have values in
webcam_home = open("home.txt", "r")
rows = webcam_home.readlines();
for row in rows:
print(">", row)
A = row
print("6",int("A")+1,"abc")
webcam_home.close()
Here is the answer to my problem: I ran your code with line print("6",int("A")+1,"abc") replaced with print("6",int(A)+1,"abc") and got no errors. – L. Kolar
My issue was a corrupted SD Card. I replaced it with my back up and tried what L.Kolar said and life is good again. It worked! I spent waaaay too many hours getting to this point and thank everyone who tried to help me, with special thanks to L.Kolar.
I did some work on trying to get MySQL running and think I must have altered something to corrupt my SD card during the process.

Updating a utility to show the date last modified

I am creating SIMPLE LOG FILE UTLITY gui using python. Each time I run the program, the source file is copied to the destination file and the source file is deleted. When the utility is started I want the display to say "The Log file was last updated (date goes here)". I have created a function named modification() using os.path.getmtime. How do I use this function to display the date?
You can find the answers on the Python docs :
The getmtime function (http://docs.python.org/library/os.path.html#os.path.getmtime) returns the number of seconds
Thanks to the Time module (http://docs.python.org/library/time.html), you can convert the number you get into local time (localtime()) or UTC time (with gmtime()).
Then, you just have to display it with your GUI toolkit as Dhaivat Pandya pointed out.
Regards,
Max
Make it return the date as a string, and then display it with your GUI toolkit.

win32com Excel data input error

I'm exporting results of my script into Excel spreadsheet. Everything works fine, I put big sets of data into SpreadSheet, but sometimes an error occurs:
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 550, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, 'Exception.', (0, None, None, None, 0, -2146777998), None)***
I suppose It's not a problem of input data format. I put several different types of data strings, ints, floats, lists and it works fine. When I run the sript for the second time it works fine - no error. What's going on?
PS. This is code that generates error, what's strange is that the error doesn't occur always. Say 30% of runs results in an error. :
import win32com.client
def Generate_Excel_Report():
Excel=win32com.client.Dispatch("Excel.Application")
Excel.Workbooks.Add(1)
Cells=Excel.ActiveWorkBook.ActiveSheet.Cells
for i in range(100):
Row=int(35+i)
for j in range(10):
Cells(int(Row),int(5+j)).Value="string"
for i in range(100):
Row=int(135+i)
for j in range(10):
Cells(int(Row),int(5+j)).Value=32.32 #float
Generate_Excel_Report()
The strangest for me is that when I run the script with the same code, the same input many times, then sometimes an error occurs, sometimes not.
This is most likely a synchronous COM access error. See my answer to Error while working with excel using python for details about why and a workaround.
I can't see why the file format/extension would make a difference. You'd be calling the same COM object either way. My experience with this error is that it's more or less random, but you can increase the chances of it happening by interacting with Excel while your script is running.
edit: It doesn't change a thing. Error occurs, but leff often. Once in 10 simulations while with .xlsx file once in 3 simulations. Please help
The problem was with the file I was opening. It was .xlsx , while I've saved it as .xls the problem disappeared. So beware, do not ever use COM interface with .xlsx or You'll get in trouble !
You should diseable excel interactivity while doing this.
import win32com.client
def Generate_Excel_Report():
Excel=win32com.client.Dispatch("Excel.Application")
#you won't see what happens (faster)
Excel.ScreenUpdating = False
#clics on the Excel window have no effect
#(set back to True before closing Excel)
Excel.Interactive = False
Excel.Workbooks.Add(1)
Cells=Excel.ActiveWorkBook.ActiveSheet.Cells
for i in range(100):
Row=int(35+i)
for j in range(10):
Cells(int(Row),int(5+j)).Value="string"
for i in range(100):
Row=int(135+i)
for j in range(10):
Cells(int(Row),int(5+j)).Value=32.32 #float
Excel.ScreenUpdating = True
Excel.Interactive = True
Generate_Excel_Report()
Also you could do that to increase your code performance :
#Construct data block
string_line = []
for i in range(10)
string_line.append("string")
string_block = []
for i in range(100)
string_block.append(string_line)
#Write data block in one call
ws = Excel.Workbooks.Sheets(1)
ws.Range(
ws.Cells(35, 5)
ws.Cells(135,15)
).Values = string block
I had the same error while using xlwings for interacting with Excel. xlwings also use win32com clients in the backend.
After some debugging, I realized that this error pops up whenever the code is executed and the excel file (containing data) is not in focus. In order to resolve the issue, I simply select the file which is being processed and run the code and it always works for me.

Categories