Re: [Tutor] Collating date data from a csv file

2019-05-14 Thread Dave Hill
Something else to have a look at, but it might have to wait for the 
longer winter nights :-)


On 14/05/2019 06:20, Ben Hancock via Tutor wrote:

On Sun, May 12, 2019 at 07:17:53PM +0100, Alan Gauld via Tutor wrote:

On 12/05/2019 11:27, Dave Hill wrote:


I found out by accident that the Megger PAT 420 data backup is actually
an SQLite database, so that is my route for access. Having played with
Python on Raspberry Pi's, I thought I would explore Python for data
processing, and now, I have a set of programs which extract SQLite, to
'csv' then collate/process this data and produce a multi-page ODS
spreadsheet document, which lists tests by location. I also have an
application which extracts appliances requiring testing within a  
+/- 30

day window, so I have a target for testing.


You could do it all in native SQLite SQL of course.
You can tell  sqlite to output its results in Excel
CSV format and to a file rather than (or in addition to)
stdout.

So you can write a standard query and have it generate
your Excel readable file directly.

You can then automate that as a batch job in the OS...
Assuming you run the same reports regularly.

Much as I love Python sometimes the native tools are
even better...



I wonder if `pandas` would also be a helpful library for what you're 
describing? It has a `pandas.read_sql` function to read data from a 
SQL database into a pandas dataframe, which you then can manipulate:


https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html 




Good luck!

--
Ben Hancock
https://elwha1.github.io
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Collating date data from a csv file

2019-05-12 Thread Dave Hill

Hi David,

Firstly, thank you for your reply.

One condition of my agreeing to undertake PAT was that I got a PAT 
machine that stored the data, as I am better at programming than paperwork!


I have a Megger PAT 420 which provides a data backup to a USB stick, and 
thence transfer to my laptop, which is network connected a dual HDD 
system (Buffalo), which automatically copies the main HDD to the slave HDD.


I found out by accident that the Megger PAT 420 data backup is actually 
an SQLite database, so that is my route for access. Having played with 
Python on Raspberry Pi's, I thought I would explore Python for data 
processing, and now, I have a set of programs which extract SQLite, to 
'csv' then collate/process this data and produce a multi-page ODS 
spreadsheet document, which lists tests by location. I also have an 
application which extracts appliances requiring testing within a  +/- 30 
day window, so I have a target for testing.


My biggest problem is locating kit, and keeping up with 
removals/disposals and new acquisitions, but the guys are getting a bit 
better at communication!


I thought it would be useful to the 'management' to have a handle on 
progress, and stats on tested/new/disposed, etc, hence the latest question.


I convert the datetimestamp to Gregorian ordinal date, as this is easier 
to use in accessing the resulting 'defaultdict', do the counting and 
then convert the date back to something comprehensible for writing to an 
ODS spreadsheet.


Having seen todays posts I am going to look at wxPython, as a front-end 
(and possibly display?)


Thank you for your consideration

Dave

On 12/05/2019 04:20, David L Neil wrote:

Hi Dave,

I also volunteer to do PAT safety testing during my "20% time". 
Clambering around Snowdonia as a boy, I eschewed* the Rheilffordd yr 
Wyddfa/SMR in favor of shanks' pony...


* OK, I was made to...! For the good of my soul???


On 9/05/19 8:04 AM, Dave Hill wrote:
I have a csv file which details the results of equipment tests, I 
carry out PAT testing as a volunteer at a heriatge railway in N. 
Wales. I want to extract how many items were tested on each test day. 
So far I have generated a List of test dates, but I am now stalled at 
how to efficiently count numbers tested on each date.


Can I have a list of tuples, where one item is the date and the 
second the count?


or is there a better construct?

Thanks in advance,

Dave

For completeness, I have listed below an extract from a target file, 
where the 10 digit number is the UNIX timestamp


182 1515001232
 Toaster 13 2000 1
183 1515001259    Contact Grill 13 2000 1
245 1515001367
 3G Cube Adaptor 13 0 1
246 1515001396     13A IEC Lead 5 0 1
248 1515001415
 Worktop Light 3 30 1
420 1515001440
 Fly killer 0 0 1
424 1515001461
 Dairy fridge 13 0 1
427 1513277293    Fire 13 0 1
429 1515001489
 Toaster Avanti 13 0 1



When you say "target file", is this coming off the tester via a link 
cable to your PC, or are you capturing by hand to a spreadsheet?


A tactic which many people 'miss' is that a workbook may contain 
multiple spreadsheets, and that the data on one spreadsheet may be 
auto-magically 'copied' onto another. Thus if the above is data coming 
off the PAT into one spreadsheet, I would immediately create a more 
meaningful sheet, 'for human consumption', which has column headings 
and converts (re-formats) the timestamp into a readable date (as 
suggested elsewhere), but is otherwise pretty-much a direct copy. We 
now have a sheet used for data capture/computer processing and 
something separate (and prettier) as a report/presentation for people.


From the spec, above, we are only interested in the date. Remember 
that considering the whole timestamp only makes life confusing. So 
convert them (only) to dates. These can be strings because Python 
compares strings as easily as dates!  The time component could be 
retained if sequence (of testing) might be important.


The sad reality is that a daily count could be accomplished in either 
LO-Writer or MS-Excel. No reason why you shouldn't use Python though.


(Assuming that the data appears in (forward or reverse) date sequence) 
Read-in the data sheet/CSV file, row-by-row, taking note of the date 
of the first data-entry, and starting to count from one. Then 
increment for each row where the date matches. When the dates don't 
match, report, reset the counter, and note the new date.


How will you lay-out and present this report? Another spreadsheet? 
Screen? Paper?


When you say "count numbers tested on each date", the above method 
will let you know a (single) daily total of tests-performed.


Did you (also) mean that you want to track how many of tests were 
performed within categories of devices, eg how many toasters 

Re: [Tutor] Collating date data from a csv file

2019-05-09 Thread Dave Hill

Thank you, I now have

defaultdict(, {736697: 10, 736677: 14, 736980: 9, 737109: 
50, 736919: 15, 736652: 19, 736502: 14, 736710: 2, 736674: 6, 736672: 5, 
736933: 2, 736932: 6, 736658: 7, 736671: 5, 736499: 6, 736707: 4, 
737181: 4, 736686: 2, ...


where the first number is the proleptic Gregorian ordinal of the date 
8-) ( I had to look up what proleptic meant)


This means I can access the elements by the ordinal of the date, for 
later processing, and extraction to a spreadsheet


Dave


On 09/05/2019 04:08, Cameron Simpson wrote:

On 08May2019 21:04, Dave Hill  wrote:
I have a csv file which details the results of equipment tests, I 
carry out PAT testing as a volunteer at a heriatge railway in N. 
Wales. I want to extract how many items were tested on each test day. 
So far I have generated a List of test dates, but I am now stalled at 
how to efficiently count numbers tested on each date.


Can I have a list of tuples, where one item is the date and the 
second the count?


Not as such, because you can't modify a tuple (so you can't update the 
count part). But you could use a 2 element list.



or is there a better construct?


Oh definitely. The easiest thing would be a defaultdict(int). Example:

 from collections import defaultdict
 ...
 by_date = defaultdict(int)
 for row in csvdata:
   timestamp = row[1]  # based on your example data
   # get the date from the timestamp
   date = ...
   by_date[date] += 1

A defaultdict is a dict which magicly makes missing elements when they 
get access, using a factory function you supply. Here we're using 
"int" as that factory, as int() returns zero.


I presume you've got the timestamp => date conversion sorted?

Cheers,
Cameron Simpson 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Collating date data from a csv file

2019-05-08 Thread Dave Hill
I have a csv file which details the results of equipment tests, I carry 
out PAT testing as a volunteer at a heriatge railway in N. Wales. I want 
to extract how many items were tested on each test day. So far I have 
generated a List of test dates, but I am now stalled at how to 
efficiently count numbers tested on each date.


Can I have a list of tuples, where one item is the date and the second 
the count?


or is there a better construct?

Thanks in advance,

Dave

For completeness, I have listed below an extract from a target file, 
where the 10 digit number is the UNIX timestamp


182 1515001232
Toaster 13  20001
183 1515001259     Contact Grill13  20001
245 1515001367
3G Cube Adaptor 13  0   1
246 1515001396      13A IEC Lead5   0   1
248 1515001415
Worktop Light   3   30  1
420 1515001440
Fly killer  0   0   1
424 1515001461
Dairy fridge13  0   1
427 1513277293     Fire 13  0   1
429 1515001489
Toaster Avanti  13  0   1

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] systemd

2019-03-03 Thread Dave Hill

Thank you - registering with Linux Mint

On 03/03/2019 16:01, Alan Gauld via Tutor wrote:

On 03/03/2019 14:46, Dave Hill wrote:


on power up, and I thought that I would use 'systemd'.

This is really a Linux question not Python so you might like to try the
Mint forums too. They are usually pretty responsive.


 [Service]
 Type=idle

 User=pi
 ExecStart=/bin/bash /home/pi/Code/testVideo.sh

 Restart=no
 RestartSec=0
where 'testVideo.sh'

 ## Dave Hill, 28/02/2019

 # 2 = HDMI, 1 = headphones, 0 = Auto
 amixer cset numid=3 1

 python3 /home/pi/Code/TestVideo#6.py CLIP0026.MP4 20 DEBUG

To be honest I'm surprised that works.
I'd expected bash to interpret the # as a comment delimiter!
But I tried it and it seems ok, you live and learn...


Is there a way in which I can have automatic restart but also have a way
of exiting?

That's the Linux bit... :-)


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] systemd

2019-03-03 Thread Dave Hill

Hi,

I am nearly ready for the new season on the Heritage railway I volunteer 
on and I am putting the final touches to a revamped 'runaway train' 
attraction in the museum. The last act is to get the code to auto-start 
on power up, and I thought that I would use 'systemd'.


The code runs on a Raspberry Pi;

   via the GPIO: sensing an input, reed switch, and controlling three
   outputs; smoke machine, fan and vibrating floor.

   on activation a video is played, at 8 times real speed, which is
   viewed through a mock-up of a loco cab.

I can run a program using:

   [Unit]
   Description=TestVideo Service
   After=multi-user.target

   [Service]
   Type=idle

   User=pi
   ExecStart=/bin/bash /home/pi/Code/testVideo.sh

   Restart=no
   RestartSec=0

   [Install]
   WantedBy=multi-user.target

where 'testVideo.sh'

   ## Dave Hill, 28/02/2019

   # 2 = HDMI, 1 = headphones, 0 = Auto
   amixer cset numid=3 1

   python3 /home/pi/Code/TestVideo#6.py CLIP0026.MP4 20 DEBUG

   exit 0

as I want to control the audio output, in this case direct audio to the 
Raspberry Pi stereo output.


The program runs an infinite loop that can be exited by Cntrl-C

I would like to take advantage of the 'restart' functionality, but I 
still wish to have a method of exiting


   i.e. Restart=always

Is there a way in which I can have automatic restart but also have a way 
of exiting?


Thanks in advance,

Dave

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.Popen()

2018-12-03 Thread Dave Hill
The combination of installing Python 3.7 on RasPi and removing the 
StringIO() cures the error.


I now get the statistics and the 'have a nice day' output from omxplayer.

I just need to find out how to invoke the idle 3.7, rather than idle 
3.5, but I think that is a question for the RasPi forum.


Thank you.

Dave

On 03/12/2018 16:27, Mats Wichmann wrote:

On 12/2/18 3:29 AM, Dave Hill wrote:


Having 'graduated' to Python 3.7, I thought I would explore
subprocess.Popen, and put the code in a Class, see code below. The video
runs, but an error occurs, which I do not understand, see further below

the error happens in the except clause of your try block ...


Traceback (most recent call last):

...

   File "/home/pi/Code/VideoPlayer.py", line 51, in playVideo
 out = omxp.communicate()

...

   File "/usr/lib/python3.5/selectors.py", line 39, in _fileobj_to_fd
 "{!r}".format(fileobj)) from None
ValueError: Invalid file object: <_io.BufferedReader name=8>

You can see that the call to communicate() is the one without arguments,
so it's in your cleanup code.   You should catch the specific exception
you expect could happen here, which is probably a timeout - but you
can't tell because you don't specify it.


     try:
     out = omxp.communicate(timeout=self.timeout)
     print("Try outs =  ", StringIO(out))
     except:
     omxp.kill()
     out = omxp.communicate()
     print("Except outs =  ", StringIO(out))

use

   except TimeoutExpired:

then it looks like the file descriptor for the second communicate is no
longer valid... here's a larger chunk from subprocess that shows what it
is raising and how it got there:

 if isinstance(fileobj, int):
 fd = fileobj
 else:
 try:
 fd = int(fileobj.fileno())
 except (AttributeError, TypeError, ValueError):
 raise ValueError("Invalid file object: "
  "{!r}".format(fileobj)) from None


In other words, it's raising the ValueError you see  because it's not a
file object. The "from None" part suppresses the context from the
original exception.

Note that communicate returns a tuple so your 'out' is actually a tuple,
and this is likely what is going wrong - by calling StringIO(out) in the
try: you are causing an exception which isn't the exception one would
expect; by not being explicit in your except: you catch that error and
take cleanup steps that are not appropriate - your video probably
finished normally.

hopefully this will help debug things...

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.Popen()

2018-12-03 Thread Dave Hill
I had not spotted that! It appears that, although I have 3.7 on my 
laptop, 3.7 is not a part of the latest standard Raspbian release. I 
will install this later today and try again.


Dave

On 03/12/2018 10:12, Alan Gauld via Tutor wrote:

On 02/12/2018 10:29, Dave Hill wrote:


Having 'graduated' to Python 3.7, I thought I would explore
Traceback (most recent call last):
File "/home/pi/Code/TestVideo#4.py", line 31, in 
  player.playVideo(FILE, 'HDMI')
File "/home/pi/Code/VideoPlayer.py", line 51, in playVideo
  out = omxp.communicate()
File "/usr/lib/python3.5/subprocess.py", line 801, in communicate
  stdout, stderr = self._communicate(input, endtime, timeout)

The first thing I notice is that you say you are using
Python 3.7 yet the libs appear to be 3.5.

It could be some kind of path problem?

Or maybe how you start Python. Do you explicitly call python37?

I don't have the time to go through the code in detail just now.
If nobody else picks it up I'll take a closer look later.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess.Popen()

2018-12-02 Thread Dave Hill
I am a volunteer at a Heritage Railway in N.Wales and, amongst other 
things, I provide electronics and software for various exhibits in the 
museum. I use the Raspberry Pi to provide various video presentations, 
employing the omxplayer.


I am in the process of updating an application known as the 'Runaway 
Train', originally written some 4ish years ago, as it has started to 
exhibit intermittent faults. This involves playing a video (at 8 times 
normal speed), via two TV screens, of a narrow gauge train ride from the 
view of the locomotive driver, on request, with the visitor located in a 
replica footplate, in which the floor vibrates and smoke emanates.


As I learn more Python I wanted to improve the interaction with 
omxplayer. In the original application I called omxplayer using Popen


__

    omxp = Popen(['omxplayer', MOVIE_PATH])

followed by

    # wait for video process to finish
    omxp.wait()

__

Having 'graduated' to Python 3.7, I thought I would explore 
subprocess.Popen, and put the code in a Class, see code below. The video 
runs, but an error occurs, which I do not understand, see further below


__

# Import subprocess
import subprocess

from io import StringIO

class Player:

    def __init__(self, path, timeout ):

    self.path = path
    self.timeout = timeout

    def playVideo(self, filename, audio):

    MOVIE_PATH = self.path + filename

    if ( audio == "HDMI" ):
    omxp = subprocess.Popen(['omxplayer', '-s', '-o', 'hdmi',\
MOVIE_PATH],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    else:
    # Call omxplayer - audio to Analog Port
    omxp = subprocess.Popen(['omxplayer', '-s', '-o', 'local',\
MOVIE_PATH],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

    try:
    out = omxp.communicate(timeout=self.timeout)
    print("Try outs =  ", StringIO(out))
    except:
    omxp.kill()
    out = omxp.communicate()
    print("Except outs =  ", StringIO(out))

__

Traceback (most recent call last):
  File "/home/pi/Code/TestVideo#4.py", line 31, in 
player.playVideo(FILE, 'HDMI')
  File "/home/pi/Code/VideoPlayer.py", line 51, in playVideo
out = omxp.communicate()
  File "/usr/lib/python3.5/subprocess.py", line 801, in communicate
stdout, stderr = self._communicate(input, endtime, timeout)
  File "/usr/lib/python3.5/subprocess.py", line 1437, in _communicate
selector.register(self.stdout, selectors.EVENT_READ)
  File "/usr/lib/python3.5/selectors.py", line 351, in register
key = super().register(fileobj, events, data)
  File "/usr/lib/python3.5/selectors.py", line 237, in register
key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
  File "/usr/lib/python3.5/selectors.py", line 224, in _fileobj_lookup
return _fileobj_to_fd(fileobj)
  File "/usr/lib/python3.5/selectors.py", line 39, in _fileobj_to_fd
"{!r}".format(fileobj)) from None
ValueError: Invalid file object: <_io.BufferedReader name=8>

__

From previous discussions, where do I sit in the demographics! I 
graduated from a degree, that was 95% physics with a small amount of 
electronics, spent 30 years as essentially an electronics engineer, 
during which time I wrote software using Fortran, Basic, Pascal (HP) and 
C++, typically for embedded applications. I have been retired for 10 
years, and occasionally play trains.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there a better way

2018-11-07 Thread Dave Hill
I have an sqlite database as a source {Asset and Test data from a Megger 
PAT Tester}, which contains a number of tables, and I end up with an 
OpenOffice spreadsheet, with numerous sheets


The data is proceesed in three parts, each using a separate Class.

I extract the useful tables, and store them as '.csv' versions. {Class#1}

I then need to correlate data from various tables, and sort into 
locations, again storing them as '.csv' versions. {Class#2}


Finally, I write all of the locations as separate sheets in an 
OpenOffice spreadsheet. {Class#3}


At this final stage I am converting table index numbers to the relevant 
string.


For example, from the '.csv' file the : TestGroupIndex [1] => Test Group 
['SC2']


'.csv' file for a location

AssetIndex  AssetId Description TestGroupIndex  RetestFrequency
106 43  Router  1   24
164 25  500 Drill   8   24
167 26  110v Ext Lead   11  24
173 37  Router DW625E   1   24
180 47  Vacuum  1   24
181 48  110v Ext11  24

sheet from '.ods' file

Asset   Asset   
TestTestNext
Index   Id  Description Group   FreqTest
106 43  Router  ['SC2'] 24  24/11/19
164 25  500 Drill   ['TO2'] 24  17/12/19
167 26  110v Ext Lead   ['EL3'] 24  24/11/19
173 37  Router DW625E   ['SC2'] 24  12/10/20
180 47  Vacuum  ['SC2'] 24  27/12/19
181 48  110v Ext['EL3'] 24  17/12/19

Test Group '.csv'

TestGroupIndex  Class   Description TestGroupId VoltageOutput
1   2   Class 2 Double insulatedSC2 230
2   1   Standard class 1 earthedSC1 230

The test group table has 30 entries but the index range is 1:31, i.e. 
one test group has been deleted at some point in the past, and the 
numbering is out of my control.


To access the test group I read the testgroup.csv file to a numpy array, 
inside {Class#3}, with two blanks, one for [0], and the other deleted group.


class OdsProcesses:

    def __init__(self, path, filename, noGroups):

        .

        .

    self.group = np.zeros(((self.noGroups + 1), 1), dtype = 
np.dtype('U10'))  # 10-character string


    def extract_TestGroup(self):

    # Open Test Group file for reading
    groupFilename = self.path
    groupFilename += self.filename
    groupFilename += self.TG_suffix
    testGroup = csv.DictReader(open(groupFilename, 'r'))

  # Loop through all Data
    for row in testGroup:
    index = int(row["TestGroupIndex"])
    self.group[index] = row["TestGroupId"]


    def get_TestGroup(self, index):

    groupStr = self.group[index]

    def writeODSData(self, sheet, roomNum):

        .

        .

    groupID = self.get_TestGroup(group)

This works but feels 'clumpy', and I have a feeling that there is a 
better way, but I have run out of ideas.


I am running Python 3.7.0, on a Windows 10 PC

Thank you for any assistance

Dave




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem compiling code from GitHub

2018-09-02 Thread Dave Hill

I now have 'odswriter' working, thank you.

I, eventually, uninstalled all versions of python and cleaned out as 
many references to python and odswriter as I could find. I then 
installed 3.7, and odswriter using


$ cd odswriter
$ python setup.py install

I guess that the first attempt at the latter steps was thwarted by some path 
problem re. Windows?

On 29/08/2018 14:04, Oscar Benjamin wrote:

On Mon, 27 Aug 2018 at 13:18, Dave Hill  wrote:

I have found 'odswriter' on GitHub
https://github.com/mmulqueen/odswriter which appears to provide what I
want. However, I have come to a halt, due to the limitation of my knowledge.

I admit that I am confounded as to where/how to access this code.

There are two ways. The code is there in github because that's where
the author(s) are saving their work on it and where people could
contribute to it.

Normally as a "user" of the odswriter code you wouldn't access it from
there. If you did want to access it from github in order to use the
code you would normally use the git program to download it:

 $ git clone https://github.com/mmulqueen/odswriter

Alternatively you can download the .zip file from github using your
browser and extract it. Either way you then need to *install* the
package to use it:

 $ cd odswriter
 $ python setup.py install

However as I said before someone who simply wants to use the odswriter
code (and not contribute to writing it) would not normally access the
code from github since Python has a better place for this which is
PyPI. You can see the PyPI page for odswriter here:
https://pypi.org/project/odswriter/

Again though you wouldn't normally download the code from PyPI using
the web browser. Python comes with a program called pip which can
download and install it for you. So the command is:

 $ pip install odswriter

I don't know why Steve has difficulty with that but this is the
easiest, fastest, officially-recommended etc. way to install Python
packages.


I am using Python 3.6.4, in IDLE on a PC running windows.

I am using the following code as a starting point , Test_ODS#1.py

 import datetime
 import decimal
 ##import odswriter as ods
 try:
  from OdsWriter import odswriter as ods
 except RuntimeError:
  print("Error importing OdsWriter!")

I have just installed odswriter in Python 3.6, on Linux, using pip and
I get this:

 >>> from OdsWriter import odswriter as ods
 Traceback (most recent call last):
   File "", line 1, in 
 ModuleNotFoundError: No module named 'OdsWriter'

However if I instead write

 >>> from odswriter import ODSWriter

then it works fine. The package name odswriter should be all
lower-case. This may not show an error on Windows because you may be
using a case-insensitive filesystem but you should fix it anyway. The
class-name ODSWriter needs to exactly match each upper and lower-case
letter because Python is much fussier than Windows file systems.

I think that misspelling the capitals in a package name can lead to
import problems although I don't know if that explains the problem
you're having. Most likely that is because you haven't "installed" the
code correctly.

--
Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem compiling code from GitHub

2018-08-28 Thread Dave Hill

I did as suggested but with the same result.

I am now looking at extracting the code from the the separate files to 
form a single module, and hopefully get a result.


On 27/08/2018 14:14, Steven D'Aprano wrote:

Hi Dave, and welcome!


On Mon, Aug 27, 2018 at 12:14:33PM +0100, Dave Hill wrote:


I have found 'odswriter' on GitHub
https://github.com/mmulqueen/odswriter which appears to provide what I
want. However, I have come to a halt, due to the limitation of my knowledge.

[...]



I get the following error

Traceback (most recent call last):
   File "C:\Code\Python\ODS_Writer\Test_ODS#1.py", line 5, in 
     from OdsWriter import odswriter as ods
   File "C:\Code\Python\ODS_Writer\OdsWriter.py", line 7, in 
     from . import ods_components
ImportError: attempted relative import with no known parent package

I have put the code from GitHub in various locations

That sounds like the problem. Some libraries are pretty forgiving about
where they are, some not so much. Some come with detailed installation
instructions, some don't.

This appears to be in the second category of both cases.

I would start by carefully deleting the code from Github (or at least
moving it out of the way) first, then installing it again.

Try installing it using the pip command. Open up a command line console.
I think you do this under Windows by typing Ctrl-R ("Run") then entering
"cmd", You ought to get a text window with a prompt looking something
like this:

 C:\ %

or similar. (If in doubt, ask.)

Try entering the command

 pip --version

and if you get an error like "pip not found" or similar, try this:

python36 -m ensurepip --default-pip
python36 -m pip install --upgrade pip setuptools wheel

after which you can then try:

pip install odswriter

I'll be honest: I don't use pip myself, every time I've tried I get
frustrated and end up installing things the old-fashioned manual way
which is theoretically "harder" but it works for me. And everyone else
swears by pip. (I just swear at it, especially the horrible colours it
likes to use.)

But if you get any errors, please don't hesitate to copy and paste them
here (DON'T take a screen shot) so we can read them and advise you.


There's a tutorial here with more detail:

https://packaging.python.org/tutorials/installing-packages/





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem compiling code from GitHub

2018-08-27 Thread Dave Hill

Hi,

As a volunteer on a Welsh Heritage Railway I undertake their Electrical 
Equipment testing, for which I use a Megger PAT420. This device stores 
data in 'sqlite', which using Python I can read and generate a number of 
reports in 'csv' format. I now wish to collate asset data for various 
locations, and as I use OpenOffice I want to generate an 'ods' document 
with a 'sheet' for each location.


At present I generate a 'csv' file for each location, but as there are 
20 locations this is a bit cumbersome. I use the 20 locations as a 
method to make the handing of over 500 assets somewhat manageable.


I have found 'odswriter' on GitHub 
https://github.com/mmulqueen/odswriter which appears to provide what I 
want. However, I have come to a halt, due to the limitation of my knowledge.


I admit that I am confounded as to where/how to access this code.

I am using Python 3.6.4, in IDLE on a PC running windows.

I am using the following code as a starting point , Test_ODS#1.py

   import datetime
   import decimal
   ##import odswriter as ods
   try:
    from OdsWriter import odswriter as ods
   except RuntimeError:
    print("Error importing OdsWriter!")

   # Single sheet mode
   with ods.writer(open("test.ods","wb")) as odsfile:
    odsfile.writerow(["String", "ABCDEF123456", "123456"])
    # Lose the 2L below if you want to run this example code on
   Python 3, Python 3 has no long type.
    odsfile.writerow(["Float", 1, 123, 123.123,
   decimal.Decimal("10.321")])
    odsfile.writerow(["Date/DateTime", datetime.datetime.now(),
   datetime.date(1989, 11, 9)])
    odsfile.writerow(["Time",datetime.time(13,
   37),datetime.time(16, 17, 18)])
    odsfile.writerow(["Bool", True, False, True])
    odsfile.writerow(["Formula", 1, 2, 3,
   ods.Formula("IF(A1=2,B1,C1)")])

   # Multiple sheet mode
   with ods.writer(open("test-multi.ods","wb")) as odsfile:
    bears = odsfile.new_sheet("Bears")
    bears.writerow(["American Black Bear", "Asiatic Black Bear",
   "Brown Bear", "Giant Panda", "Qinling Panda",
 "Sloth Bear", "Sun Bear", "Polar Bear",
   "Spectacled Bear"])
    sloths = odsfile.new_sheet("Sloths")
    sloths.writerow(["Pygmy Three-Toed Sloth", "Maned Sloth",
   "Pale-Throated Sloth", "Brown-Throated Sloth",
 "Linneaeus's Two-Twoed Sloth", "Hoffman's
   Two-Toed Sloth"])

I get the following error

   Traceback (most recent call last):
  File "C:\Code\Python\ODS_Writer\Test_ODS#1.py", line 5, in 
    from OdsWriter import odswriter as ods
  File "C:\Code\Python\ODS_Writer\OdsWriter.py", line 7, in 
    from . import ods_components
   ImportError: attempted relative import with no known parent package

I have put the code from GitHub in various locations subject to my 
limited knowledge of Python, but I have no idea what the following 
extract means, and searching online on & off for two days has proved 
unfruitful.


   from __future__ import unicode_literals
   from zipfile import ZipFile
   import decimal
   import datetime
   from xml.dom.minidom import parseString

   from . import ods_components
   from .formula import Formula

I understand the use of 'import' and have written my own modules, but 
from . import ods_components has me floored.


Thank you in advance for any help.

Dave





import datetime
import decimal
##import odswriter as ods
try:
from OdsWriter import odswriter as ods
except RuntimeError:
print("Error importing OdsWriter!")

# Single sheet mode
with ods.writer(open("test.ods","wb")) as odsfile:
odsfile.writerow(["String", "ABCDEF123456", "123456"])
# Lose the 2L below if you want to run this example code on Python 3, 
Python 3 has no long type.
odsfile.writerow(["Float", 1, 123, 123.123, decimal.Decimal("10.321")])
odsfile.writerow(["Date/DateTime", datetime.datetime.now(), 
datetime.date(1989, 11, 9)])
odsfile.writerow(["Time",datetime.time(13, 37),datetime.time(16, 17, 18)])
odsfile.writerow(["Bool", True, False, True])
odsfile.writerow(["Formula", 1, 2, 3, ods.Formula("IF(A1=2,B1,C1)")])

# Multiple sheet mode
with ods.writer(open("test-multi.ods","wb")) as odsfile:
bears = odsfile.new_sheet("Bears")
bears.writerow(["American Black Bear", "Asiatic Black Bear", "Brown Bear", 
"Giant Panda", "Qinling Panda", 
 "Sloth Bear", "Sun Bear", "Polar Bear", "Spectacled Bear"])
sloths = odsfile.new_sheet("Sloths")
sloths.writerow(["Pygmy Three-Toed Sloth", "Maned Sloth", "Pale-Throated 
Sloth", "Brown-Throated Sloth",
 "Linneaeus's Two-Twoed Sloth", "Hoffman's Two-Toed Sloth"])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor