Re: stderr writting before stdout

2020-05-25 Thread Rhodri James

On 24/05/2020 05:27, Souvik Dutta wrote:

Is there any precedence or priority order by which sys.stderr.write() and
sys.stdout.write() works.


No.

--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Writing output of function to a csv file

2020-05-25 Thread Ciarán Hudson
Hi,

In the code below, which is an exercise I'm doing in class inheritance, almost 
everything is working except outputting my results, which as the function 
stock_count, to a csv.
stock_count is working in the code.
And I'm able to open and close the csv called cars, but the stock_count output 
is not being written to the file.
Any suggestions?

There are 2 python files as the exercise is about class inheritance.
I'll paste the code from both.

cars.py

# Define a class for my car

class Car(object):
# implement the car object.

def __init__(self):
self.__colour = ''
self.__make = ''
self.__mileage = 0
self.engineSize = ''

def getColour(self):
return self.__colour

def getMake(self):
return self.__make

def getMileage(self):
return self.__mileage

def setColour(self, colour):
self.__colour = colour

def setMake(self, make):
self.__make = make

def setMileage(self, mileage):
self.__mileage = mileage

def paint(self, colour):
self.__colour = colour
return self.__colour

def move(self, distance):
self.__mileage = self.__mileage + distance
return self.__mileage


class ElectricCar(Car):
 
def __init__(self):
self.__numberFuelCells = 1
 
def getNumberFuelCells(self):
return self.__numberFuelCells

def setNumberFuelCells(self, value):
self.__numberFuelCells

class PetrolCar(Car):
   
def __init__(self):
self.__choke = 0

def __getChoke(self):
return self.__choke

def __setChoke(self, value):
self.__choke = value

class DieselCar(Car):
   
def __init__(self):
self.__dpf = 0

def __getDpf(self):
return self.__dpf

def __setDpf(self, value):
self.__dpf = value


class HybridCar(Car):
   
def __init__(self):
self.__regeneration = 0

def __getRegeneration(self):
return self.__regeneration

def __setRegeneration(self, value):
self.__regeneration = value



dealership.py
import csv
from car import Car, ElectricCar, PetrolCar, DieselCar, HybridCar



class Dealership(object):

def __init__(self):
self.electric_cars = []
self.petrol_cars = []
self.diesel_cars = []
self.hybrid_cars = []

def create_current_stock(self):
for i in range(6):
   self.electric_cars.append(ElectricCar())
for i in range(20):
   self.petrol_cars.append(PetrolCar())
for i in range(10):
   self.diesel_cars.append(DieselCar())
for i in range(4):
   self.hybrid_cars.append(HybridCar())



def stock_count(self):
print('petrol cars in stock ' + str(len(self.petrol_cars)))
print('electric cars in stock ' + str(len(self.electric_cars)))
print('diesel cars in stock ' + str(len(self.diesel_cars)))
print('hybrid cars in stock ' + str(len(self.hybrid_cars)))


def rent(self, car_list, amount):
if len(car_list) < amount:
print('Not enough cars in stock')
return
total = 0
while total < amount:
   car_list.pop()
   total = total + 1
   
   

def process_rental(self):
answer = input('would you like to rent a car? y/n')
if answer == 'y':
self.stock_count()
answer = input('what type would you like? p/e/d/h')
amount = int(input('how many would you like?'))
if answer == 'p':
self.rent(self.petrol_cars, amount)
if answer == 'd':
self.rent(self.diesel_cars, amount)
if answer == 'h':
self.rent(self.hybrid_cars, amount)
else:
self.rent(self.electric_cars, amount)
self.stock_count()

file = open("cars.csv","w")
file.write(str(self.stock_count()))
file.close()


dealership = Dealership()
dealership.create_current_stock()
proceed = 'y'
while proceed == 'y':
dealership.process_rental()
proceed = input('continue? y/n')

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing output of function to a csv file

2020-05-25 Thread MRAB

On 2020-05-25 19:00, Ciarán Hudson wrote:

Hi,

In the code below, which is an exercise I'm doing in class inheritance, almost 
everything is working except outputting my results, which as the function 
stock_count, to a csv.
stock_count is working in the code.
And I'm able to open and close the csv called cars, but the stock_count output 
is not being written to the file.
Any suggestions?


[snip]


 def stock_count(self):
 print('petrol cars in stock ' + str(len(self.petrol_cars)))
 print('electric cars in stock ' + str(len(self.electric_cars)))
 print('diesel cars in stock ' + str(len(self.diesel_cars)))
 print('hybrid cars in stock ' + str(len(self.hybrid_cars)))
 


 def process_rental(self):
 answer = input('would you like to rent a car? y/n')
 if answer == 'y':
 self.stock_count()
 answer = input('what type would you like? p/e/d/h')
 amount = int(input('how many would you like?'))
 if answer == 'p':
 self.rent(self.petrol_cars, amount)
 if answer == 'd':
 self.rent(self.diesel_cars, amount)
 if answer == 'h':
 self.rent(self.hybrid_cars, amount)
 else:
 self.rent(self.electric_cars, amount)
 self.stock_count()
 
 file = open("cars.csv","w")

 file.write(str(self.stock_count()))
 file.close()
 
In 'stock_count' you're telling it to print to the screen. Nowhere in 
that function are you telling it to write to a file.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing output of function to a csv file

2020-05-25 Thread Irv Kalb

> On May 25, 2020, at 11:25 AM, MRAB  > wrote:
> 
> On 2020-05-25 19:00, Ciarán Hudson wrote:
>> Hi,
>> In the code below, which is an exercise I'm doing in class inheritance, 
>> almost everything is working except outputting my results, which as the 
>> function stock_count, to a csv.
>> stock_count is working in the code.
>> And I'm able to open and close the csv called cars, but the stock_count 
>> output is not being written to the file.
>> Any suggestions?
> [snip]
>> def stock_count(self):
>> print('petrol cars in stock ' + str(len(self.petrol_cars)))
>> print('electric cars in stock ' + str(len(self.electric_cars)))
>> print('diesel cars in stock ' + str(len(self.diesel_cars)))
>> print('hybrid cars in stock ' + str(len(self.hybrid_cars)))
>>  def process_rental(self):
>> answer = input('would you like to rent a car? y/n')
>> if answer == 'y':
>> self.stock_count()
>> answer = input('what type would you like? p/e/d/h')
>> amount = int(input('how many would you like?'))
>> if answer == 'p':
>> self.rent(self.petrol_cars, amount)
>> if answer == 'd':
>> self.rent(self.diesel_cars, amount)
>> if answer == 'h':
>> self.rent(self.hybrid_cars, amount)
>> else:
>> self.rent(self.electric_cars, amount)
>> self.stock_count()
>>  file = open("cars.csv","w")
>> file.write(str(self.stock_count()))
>> file.close()
>> 
> In 'stock_count' you're telling it to print to the screen. Nowhere in that 
> function are you telling it to write to a file.

More specifically, your main code calls the dealership.process_rental method.  
That method calls self.stock_count() which writes to the screen. 

Then, you are attempting to write the same information to a file.  Your code 
successfully opens a file, but your next line:
file.write(str(self.stock_count()))
tries to take the output of that self.sock_count() and write that to the file.  
Your self.stock_count does not return anything, so it returns the special 
value: None.  So, the file is created, and the only thing written to the file 
is None.

Since this is a homework assignment, I won't show you how to do it (I am a 
teacher).  But you need to format the information that you want to write as a 
string and write that to a file.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing output of function to a csv file

2020-05-25 Thread Manfred Lotz
On Mon, 25 May 2020 19:25:08 +0100
MRAB  wrote:

> On 2020-05-25 19:00, Ciarán Hudson wrote:
> > Hi,
> > 
> > In the code below, which is an exercise I'm doing in class
> > inheritance, almost everything is working except outputting my
> > results, which as the function stock_count, to a csv. stock_count
> > is working in the code. And I'm able to open and close the csv
> > called cars, but the stock_count output is not being written to the
> > file. Any suggestions? 
> [snip]
> > 
> >  def stock_count(self):
> >  print('petrol cars in stock ' + str(len(self.petrol_cars)))
> >  print('electric cars in stock ' +
> > str(len(self.electric_cars))) print('diesel cars in stock ' +
> > str(len(self.diesel_cars))) print('hybrid cars in stock ' +
> > str(len(self.hybrid_cars))) 
> > 
> >  def process_rental(self):
> >  answer = input('would you like to rent a car? y/n')
> >  if answer == 'y':
> >  self.stock_count()
> >  answer = input('what type would you like? p/e/d/h')
> >  amount = int(input('how many would you like?'))
> >  if answer == 'p':
> >  self.rent(self.petrol_cars, amount)
> >  if answer == 'd':
> >  self.rent(self.diesel_cars, amount)
> >  if answer == 'h':
> >  self.rent(self.hybrid_cars, amount)
> >  else:
> >  self.rent(self.electric_cars, amount)
> >  self.stock_count()
> >  
> >  file = open("cars.csv","w")
> >  file.write(str(self.stock_count()))
> >  file.close()
> >
> In 'stock_count' you're telling it to print to the screen. Nowhere in 
> that function are you telling it to write to a file.

I think something gets written to 'cars.csv', namely the string 'None'.

-- 
Manfred

-- 
https://mail.python.org/mailman/listinfo/python-list


Custom logging function

2020-05-25 Thread zljubisic
Hi,

I have a case in which I have to use custom function for logging.
For example, all messages should go to stderr and end with '\r\n'.

Can I somehow use standard python logging module but send all message to stderr 
with '\r\n' line endings?

Regards
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Custom logging function

2020-05-25 Thread DL Neil via Python-list

On 26/05/20 8:26 AM, zljubi...@gmail.com wrote:

Hi,

I have a case in which I have to use custom function for logging.
For example, all messages should go to stderr and end with '\r\n'.

Can I somehow use standard python logging module but send all message to stderr 
with '\r\n' line endings?



- use a logging formatter (with the below, linesep) to construct 
log.msgs (and their endings)
- use the logging library's helper function to direct log.msgs to stderr 
(or wherever)



os.linesep in The Python Standard Library: os — Miscellaneous operating 
system interfaces

https://docs.python.org/3/library/os.html


stderr is the default destination for logging
Logging HOWTO https://docs.python.org/3/howto/logging.html
https://docs.python.org/3/library/logging.html

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Decorators with arguments?

2020-05-25 Thread Christopher de Vidal
Peter Otten, Cameron Simpson, thank you for your detailed replies :-) I
confess, I didn't quite understand all you were saying. (Still only an
intermediate-level programmer.) But Cameron what you said questioning my
use of decorators and maybe a class instead got me thinking. I realized
what I needed was a function within a function. Couldn't have gotten there
without your help. Working code:

#!/usr/bin/env python3
from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
import json
import mqtt
from time import sleep

def bridge(col_name):
def on_snapshot(col_snapshot, changes, read_time):
data = dict()
for doc in col_snapshot:
serial = doc.id
data[serial] = json.dumps(doc.to_dict()['value'])
for change in changes:
serial = change.document.id
mqtt_topic = col_name + '/outgoing/' + serial
if change.type.name in ['ADDED', 'MODIFIED']:
contents = data[serial]
mqtt.publish(mqtt_topic, contents)
elif change.type.name == 'REMOVED':
mqtt.publish(mqtt_topic, '')


@mqtt.incoming
def mqtt_subscribe(serial, value):
# TODO Passing a None entry to delete from MQTT doesn't trigger
this
#   callback, so it doesn't delete from Firestore. Need this ugly
#   workaround 'clear_mqtt'.
if value == 'clear_mqtt':
value = None
mqtt.publish(col_name + '/incoming/' + serial, None)
mqtt.publish(col_name + '/outgoing/' + serial, None)
db.collection(col_name).document(serial).set({'value': value})


col_watch = db.collection(col_name).on_snapshot(on_snapshot)
mqtt.subscribe(col_name + '/incoming/#', mqtt_subscribe)
return col_watch


cred = credentials.Certificate("certs/firebase.json")
firebase_admin.initialize_app(cred)
db = firestore.Client()
mqtt.connect()
adapters = list()
for collection in ['door_status', 'cpu_temp']:
adapters.append(bridge(collection))
while True:
sleep(1)
for adapter in adapters:
adapter.unsubscribe()

Christopher de Vidal

Would you consider yourself a good person? Have you ever taken the 'Good
Person' test? It's a fascinating five minute quiz. Google it.


On Fri, May 15, 2020 at 9:55 AM Peter Otten <__pete...@web.de> wrote:

> Christopher de Vidal wrote:
>
> > Help please? Creating an MQTT-to-Firestore bridge and I know a decorator
> > would help but I'm stumped how to create one. I've used decorators before
> > but not with arguments.
> >
> > The Firestore collection.on_snapshot() method invokes a callback and
> sends
> > it three parameters (collection_snapshot, changes, and read_time). I need
> > the callback to also know the name of the collection so that I can
> publish
> > to the equivalent MQTT topic name. I had thought to add a fourth
> parameter
> > and I believe a decorator is the right approach but am stumped how to add
> > that fourth parameter. How would I do this with the code below?
> >
> > #!/usr/bin/env python3
> > from google.cloud import firestore
> > import firebase_admin
> > from firebase_admin import credentials
> > import json
> > import mqtt
> >
> >
>
> firebase_admin.initialize_app(credentials.Certificate("certs/firebase.json"))
> > db = firestore.Client()
> > mqtt.connect()
> >
> >
> > def load_json(contents):
> > try:
> > return json.loads(contents)
> > except (json.decoder.JSONDecodeError, TypeError):
> > return contents
> >
> >
> > def on_snapshot(col_name, col_snapshot, changes, read_time):
> > data = dict()
> > for doc in col_snapshot:
> > serial = doc.id
> > contents = load_json(doc.to_dict()['value'])
> > data[serial] = contents
> > for change in changes:
> > serial = change.document.id
> > mqtt_topic = col_name + '/' + serial
> > contents = data[serial]
> > if change.type.name in ['ADDED', 'MODIFIED']:
> > mqtt.publish(mqtt_topic, contents)
> > elif change.type.name == 'REMOVED':
> > mqtt.publish(mqtt_topic, None)
> >
> >
> > # Start repeated code section
> > # TODO Better to use decorators but I was stumped on how to pass
> arguments
> > def door_status_on_snapshot(col_snapshot, changes, read_time):
> > on_snapshot('door_status', col_snapshot, changes, read_time)
> >
> >
> > door_status_col_ref = db.collection('door_status')
> > door_status_col_watch =
> > door_status_col_ref.on_snapshot(door_status_on_snapshot)
> >
> > # Repetition...
> > def cpu_temp_on_snapshot(col_snapshot, changes, read_time):
> > on_snapshot('cpu_temp', col_snapshot, changes, read_time)
> >
> >
> > cpu_temp_col_ref = db.collection('cpu_temp')
> > cpu_temp_col_watch = cpu_temp_col_ref.on_snapshot(cpu_temp_on_snapshot)
> > # End repeated code section
> >
> > # Start repeated code section
> > door_status_col_watch.unsubscribe()
> > cpu_temp_col_watch.unsubscribe()
> > # Repetition..

Re: Managing plug-ins

2020-05-25 Thread Benjamin Schollnick
Did you ever find anything that met your requirements?

If not, I have a prototype that I need to build out some more…

https://github.com/bschollnick/PyPlugInMgr 


I use it for some home grown utilities, but it needs to be fleshed out some 
more…
If you’re interested feel free to take a look.

- Benjamin



> On Feb 23, 2020, at 5:45 PM, DL Neil via Python-list  
> wrote:
> 
> Please recommend a library which will manage plug-ins.
> 
> 
> (Regret that searching PyPi or using a web SE results in an overwhelming 
> number of 'false positives')
> 
> Not wanting to 'reinvent the wheel, have been looking for an 'approved' way 
> to manage a set of previously-prepared routines plus user-added functionality:
> - user selects particular type of analysis (cmdLN)
> - take that string and convert to a function/method
> - 'plug-in' code could be located within application
> - 'plug-in' could be 'included' from user
> - interface standardisation/checking not part of question
> - Python3
> 
> Application is statistical analysis. Users want to control aspects such as 
> data selection/inclusion policies, other data pre-processing/massaging, 
> distribution curve to be applied, and similar.
> NB not looking for stats-code, but to easily manage a range of plug-ins from 
> which users may select to suit their particular research objective.
> -- 
> Regards,
> =dn
> -- 
> https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing output of function to a csv file

2020-05-25 Thread Ciarán Hudson
Thanks, between this message and the one below I was able to understand my 
error and fix it. I really appreciate the help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Managing plug-ins

2020-05-25 Thread DL Neil via Python-list

On 26/05/20 11:35 AM, Benjamin Schollnick wrote:

Did you ever find anything that met your requirements?

If not, I have a prototype that I need to build out some more…

https://github.com/bschollnick/PyPlugInMgr

I use it for some home grown utilities, but it needs to be fleshed out 
some more…

If you’re interested feel free to take a look.


Thanks.
Am on-the-road at present, but will take a look...
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list