PyPDF2 merge / out of memory

2016-02-21 Thread cpoline95
Hello,

There is an issue with PyPDF2 and merging file
https://github.com/mstamy2/PyPDF2/issues/189

Does anybody know an alternate library to merge PDF and produce optimized pdf 
file ?

Thanks a lot

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


Re: PyPDF2 merge / out of memory

2016-02-21 Thread Mark Lawrence

On 21/02/2016 10:41, [email protected] wrote:

Hello,

There is an issue with PyPDF2 and merging file
https://github.com/mstamy2/PyPDF2/issues/189

Does anybody know an alternate library to merge PDF and produce optimized pdf 
file ?

Thanks a lot

Clement



I did a bit of searching and found 
http://www.pdftron.com/pdfnet/features.html, which on pypi is described as:-



A top notch PDF library for PDF rendering, conversion, content 
extraction, etc


PDFNet SDK is an amazingly comprehensive, high-quality PDF developer 
toolkit for working with PDF files at all levels. Using the PDFNet PDF 
library, developers can create powerful PDF solutions and applications 
that can generate, manipulate, view, render and print PDF documents on 
Windows, Mac, and Linux.



There's also https://bitbucket.org/vasudevram/xtopdf which states it's a


This package (xtopdf) contains tools to convert various file formats 
(collectively called x) to PDF format.



Vasudev Ram I know does a lot of work with PDF so a further search 
throws up articles on using his code, including some recipes on Activestate.


Note I've used none of these myself, I just HTH.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread BartC

On 21/02/2016 07:28, Larry Hudson wrote:

On 02/20/2016 10:38 AM, [email protected] wrote:



Or can I write my own reading subroutines which can then be called like
ReadVBstyle 8, ND, NIN, NT
to make the code more readable?



ABSOLUTELY!!  Most Python programming consists of defining the functions
and classes needed, which definitely makes Python more readable.



No need for anyone to re-invent the
wheel!  ;-)


I keep seeing this in the thread. Python has all this capability, yet it 
still requires a lot of fiddly code to be added to get anywhere near as 
simple as this:


  read f, a, b, c

And this is code that is not going to be obvious to anyone starting out. 
Even accepting that syntax limitations might require this to be written as:


  readline(f, a, b, c)

I can't see a straightforward way of making this possible while still 
keeping a, b and c simple integer, float or string types (because 
Python's reference parameters don't work quite the right way).


(There is also the question of 'readline' knowing what types of values 
to read. This information would not be needed in Fortran or Basic but 
somehow needs to be supplied here, if a particular set of types is to 
imposed on the input.)


In other words, it seems this particular wheel does require re-inventing!

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


how to get the list form dictionary's values

2016-02-21 Thread davidbenny2000
  File "mainpy.py", line 81
for functionlistelement in functionlist0
   ^
SyntaxError: invalid syntax


import asyncio

def f000():
 try:
  print "000"
 except:
  print "000 exception"

def f001():
 try:
  print "001"
 except:
  print "001 exception"

def f002():
 try:
  print "002"
 except:
  print "002 exception"

def f003():
 try:
  print "003"
 except:
  print "003 exception"

def f004():
 try:
  print "004"
 except:
  print "004 exception"

machine = {}
mappedfunc = {}
functionlist000 = []
functionlist001 = []
functionlist002 = []
functionlist003 = []
functionlist004 = []

functionlist000.append('002')
functionlist001.append('000')
functionlist002.append('003')
functionlist002.append('004')

functionlist003.append('001')
functionlist004.append('001')

machine000 = {'000': functionlist000}
machine001 = {'001': functionlist001}
machine002 = {'002': functionlist002}
machine003 = {'003': functionlist003}
machine004 = {'004': functionlist004}

machine.update(machine000)
machine.update(machine001)
machine.update(machine002)
machine.update(machine003)
machine.update(machine004)

functionkey000 = {'000': f000 }
functionkey001 = {'001': f001 }
functionkey002 = {'002': f002 }
functionkey002 = {'003': f003 }
functionkey002 = {'004': f004 }

mappedfunc.update(functionkey000)
mappedfunc.update(functionkey001)
mappedfunc.update(functionkey002)
mappedfunc.update(functionkey003)
mappedfunc.update(functionkey004)

def workingthreadpool(currentnumber1, machine1):
 try:
  functionlist0 = machine1.get(currentnumber1)

  loop = asyncio.get_event_loop()
  tesks = []
  
  j = 1
  for functionlistelement in functionlist0
   tesks.append(asyncio.ensure_future(mappedfunc.get(functionlistelement)()))
   if j > 1:
workingthreadpool(functionlistelement)
   j = j + 1

  loop.run_until_complete(asyncio.wait(tesks))
  loop.close()
 except:
  print "workingthreadpool exception"

currentnumber = "000"
workingthreadpool(currentnumber, machine)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread Chris Angelico
On Mon, Feb 22, 2016 at 12:16 AM, BartC  wrote:
> On 21/02/2016 07:28, Larry Hudson wrote:
>>
>> On 02/20/2016 10:38 AM, [email protected] wrote:
>
>
>>> Or can I write my own reading subroutines which can then be called like
>>> ReadVBstyle 8, ND, NIN, NT
>>> to make the code more readable?
>
>
>> ABSOLUTELY!!  Most Python programming consists of defining the functions
>> and classes needed, which definitely makes Python more readable.
>
>
>> No need for anyone to re-invent the
>> wheel!  ;-)
>
>
> I keep seeing this in the thread. Python has all this capability, yet it
> still requires a lot of fiddly code to be added to get anywhere near as
> simple as this:
>
>   read f, a, b, c
>
> And this is code that is not going to be obvious to anyone starting out.
> Even accepting that syntax limitations might require this to be written as:
>
>   readline(f, a, b, c)
>
> I can't see a straightforward way of making this possible while still
> keeping a, b and c simple integer, float or string types (because Python's
> reference parameters don't work quite the right way).

How about:

a, b, c = readline(f)

> (There is also the question of 'readline' knowing what types of values to
> read. This information would not be needed in Fortran or Basic but somehow
> needs to be supplied here, if a particular set of types is to imposed on the
> input.)

You'd still need to solve that, one way or another. But the Pythonic
way is to distinguish between "input" and "output" parameters by
having the input parameters as parameters, and the output parameters
as the return value. And personally, I find it *way* more readable
that way; while it's perfectly possible to pass a list as a parameter
and have the function append to it, it's much clearer if your return
values are on the left of the equals sign.

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


Re: how to get the list form dictionary's values

2016-02-21 Thread Chris Angelico
On Mon, Feb 22, 2016 at 12:34 AM,   wrote:
>   File "mainpy.py", line 81
> for functionlistelement in functionlist0
>^
> SyntaxError: invalid syntax

Your actual syntax problem here is simply a missing colon. That's
easily fixed. But please, PLEASE, don't do this:

> def workingthreadpool(currentnumber1, machine1):
>  try:
>   functionlist0 = machine1.get(currentnumber1)
>
>   loop = asyncio.get_event_loop()
>   tesks = []
>
>   j = 1
>   for functionlistelement in functionlist0
>tesks.append(asyncio.ensure_future(mappedfunc.get(functionlistelement)()))
>if j > 1:
> workingthreadpool(functionlistelement)
>j = j + 1
>
>   loop.run_until_complete(asyncio.wait(tesks))
>   loop.close()
>  except:
>   print "workingthreadpool exception"

1) Indenting by a single space makes it hard to skim and see what's at
what indentation level. Indent by at least four spaces (I've seen two,
and it's still very narrow), or one tab.

2) Carrying a counter through a 'for' loop is much better done with
enumerate(). But the counter's sole purpose is to ignore the first
element, so you might want to find a completely different approach.

3) Why does this recurse anyway? Your function appends one future to
'tesks' (should that be 'tasks'?), then appends another... and then
calls itself recursively. What's that doing, exactly?

4) Bare except clauses are almost always a bad idea. In fact, if a
future version of Python raises a SyntaxWarning or even SyntaxError on
the bare except, I would see it as no loss. As of Python 2.7, it's
possible to raise an old-style class, which then won't be caught by
"except Exception:" or even "except BaseException:", but I'm pretty
sure there's nothing you can raise in Python 3 that isn't caught by
"except BaseException:". Proper exception handling generally means
either (a) catching a specific exception or list of exceptions, and
handling them; or (b) catching everything, logging them in some way,
and returning to some sort of main loop. Your code is simply reporting
the presence of an exception, nothing more, and then bailing out. Let
those exceptions bubble up to top level and be printed out!

5) Asynchronous code is way better supported in Python 3.5 than in
2.7. I strongly recommend upgrading your Python.

These considerations are less simple than the syntax issue you were
asking about, but they're also non-trivial problems. You might get
your code to _run_, but can you get it to do the right thing, even
after you tinker with it later on? Good code saves you time in the
long run.

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


Re: how to get the list form dictionary's values

2016-02-21 Thread Peter Otten
[email protected] wrote:

>   File "mainpy.py", line 81
> for functionlistelement in functionlist0
>^
> SyntaxError: invalid syntax
> 
> 
> import asyncio

[snip]

> mappedfunc = {}
> functionlist000 = []
> functionlist001 = []
> functionlist002 = []
> functionlist003 = []
> functionlist004 = []

[snip many names with numeric suffix and repeated method calls]

I have no idea what you are trying to do; however, your code looks awfully 
redundant. This is errorprone:

functionkey000 = {'000': f000 }
functionkey001 = {'001': f001 }
functionkey002 = {'002': f002 }
functionkey002 = {'003': f003 }
functionkey002 = {'004': f004 }

>   for functionlistelement in functionlist0

To answer what seems to be your actual question: a colon is missing at the 
end of this line.

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


Re: how to get the list form dictionary's values

2016-02-21 Thread Ho Yeung Lee
Hi Chris,

0 ---> 2 --> 3--> 1 ---> 0
---> 4 /

i am practicing task flow in this graph situation

when current state is 2 , there are 3 and 4 to run parallel and wait list of 
tasks finish before running to 1 , 

however i feel that my code has been wrong because 3 and 4 can not combine to 
run task 1 , 

which is the correct way to combine to run task 1?

or is this graph situation an example impossible to do in computer science?

Regards,

Martin Lee

Chris Angelico於 2016年2月21日星期日 UTC+8下午10時04分22秒寫道:
> On Mon, Feb 22, 2016 at 12:34 AM,   wrote:
> >   File "mainpy.py", line 81
> > for functionlistelement in functionlist0
> >^
> > SyntaxError: invalid syntax
> 
> Your actual syntax problem here is simply a missing colon. That's
> easily fixed. But please, PLEASE, don't do this:
> 
> > def workingthreadpool(currentnumber1, machine1):
> >  try:
> >   functionlist0 = machine1.get(currentnumber1)
> >
> >   loop = asyncio.get_event_loop()
> >   tesks = []
> >
> >   j = 1
> >   for functionlistelement in functionlist0
> >
> > tesks.append(asyncio.ensure_future(mappedfunc.get(functionlistelement)()))
> >if j > 1:
> > workingthreadpool(functionlistelement)
> >j = j + 1
> >
> >   loop.run_until_complete(asyncio.wait(tesks))
> >   loop.close()
> >  except:
> >   print "workingthreadpool exception"
> 
> 1) Indenting by a single space makes it hard to skim and see what's at
> what indentation level. Indent by at least four spaces (I've seen two,
> and it's still very narrow), or one tab.
> 
> 2) Carrying a counter through a 'for' loop is much better done with
> enumerate(). But the counter's sole purpose is to ignore the first
> element, so you might want to find a completely different approach.
> 
> 3) Why does this recurse anyway? Your function appends one future to
> 'tesks' (should that be 'tasks'?), then appends another... and then
> calls itself recursively. What's that doing, exactly?
> 
> 4) Bare except clauses are almost always a bad idea. In fact, if a
> future version of Python raises a SyntaxWarning or even SyntaxError on
> the bare except, I would see it as no loss. As of Python 2.7, it's
> possible to raise an old-style class, which then won't be caught by
> "except Exception:" or even "except BaseException:", but I'm pretty
> sure there's nothing you can raise in Python 3 that isn't caught by
> "except BaseException:". Proper exception handling generally means
> either (a) catching a specific exception or list of exceptions, and
> handling them; or (b) catching everything, logging them in some way,
> and returning to some sort of main loop. Your code is simply reporting
> the presence of an exception, nothing more, and then bailing out. Let
> those exceptions bubble up to top level and be printed out!
> 
> 5) Asynchronous code is way better supported in Python 3.5 than in
> 2.7. I strongly recommend upgrading your Python.
> 
> These considerations are less simple than the syntax issue you were
> asking about, but they're also non-trivial problems. You might get
> your code to _run_, but can you get it to do the right thing, even
> after you tinker with it later on? Good code saves you time in the
> long run.
> 
> ChrisA

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


Re: how to get the list form dictionary's values

2016-02-21 Thread Ho Yeung Lee
Peter Otten於 2016年2月21日星期日 UTC+8下午10時07分18秒寫道:
> [email protected] wrote:
> 
> >   File "mainpy.py", line 81
> > for functionlistelement in functionlist0
> >^
> > SyntaxError: invalid syntax
> > 
> > 
> > import asyncio
> 
> [snip]
> 
> > mappedfunc = {}
> > functionlist000 = []
> > functionlist001 = []
> > functionlist002 = []
> > functionlist003 = []
> > functionlist004 = []
> 
> [snip many names with numeric suffix and repeated method calls]
> 
> I have no idea what you are trying to do; however, your code looks awfully 
> redundant. This is errorprone:
> 
> functionkey000 = {'000': f000 }
> functionkey001 = {'001': f001 }
> functionkey002 = {'002': f002 }
> functionkey002 = {'003': f003 }
> functionkey002 = {'004': f004 }
> 
> >   for functionlistelement in functionlist0
> 
> To answer what seems to be your actual question: a colon is missing at the 
> end of this line.


hi Peter,

i am running this task flow in this graph,

these code are not redundant, because this writing can clearly
show the work flow

https://drive.google.com/file/d/0B7fHc_dTzkY_OGMtTGI2UnR6ZEE/view?usp=sharing


Regards,

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


Re: how to get the list form dictionary's values

2016-02-21 Thread Chris Angelico
On Mon, Feb 22, 2016 at 1:15 AM, Ho Yeung Lee  wrote:
> Hi Chris,
>
> 0 ---> 2 --> 3--> 1 ---> 0
> ---> 4 /
>
> i am practicing task flow in this graph situation
>
> when current state is 2 , there are 3 and 4 to run parallel and wait list of 
> tasks finish before running to 1 ,
>
> however i feel that my code has been wrong because 3 and 4 can not combine to 
> run task 1 ,
>
> which is the correct way to combine to run task 1?

So after task 2 completes, tasks 3 and 4 both become available (and
can run in parallel), but then task 1 must wait until both have
finished before it runs? I'm not an asyncio expert, but this sounds
like a fairly straight-forward dependency requirement. If you were to
implement these as four separate threads, you would have threads 3 and
4 raise semaphores which thread 1 blocks on; I'm sure there'll be an
equivalent in asyncio.

One way to do it would be something like this:

import asyncio

loop = asyncio.get_event_loop()

async def starter():
print("Starting!")
global t1, t2
t1 = asyncio.Task(dep1())
t2 = asyncio.Task(dep2())
print("Done!")
await dependent()

async def dep1():
print("Dependency 1")
await asyncio.sleep(3)
print("Dep 1 done.")

async def dep2():
print("Dependency 2")
await asyncio.sleep(2)
print("Dep 2 done.")

async def dependent():
await t1
await t2
print("Deps are done - dependent can run.")

loop.run_until_complete(starter())



The dependent task simply waits for each of its dependencies in turn.
It doesn't matter which one finishes first; it won't do its main work
until both are done. And if your starter and dependent are logically
connected, you can just have the 'await' lines in the middle of one
tidy function.

(Can an asyncio expert tell me how to tidy this code up, please? I'm
sure this isn't the cleanest.)

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread Jussi Piitulainen
BartC writes:

> On 21/02/2016 07:28, Larry Hudson wrote:
>> On 02/20/2016 10:38 AM, [email protected] wrote:
>
>>> Or can I write my own reading subroutines which can then be called like
>>> ReadVBstyle 8, ND, NIN, NT
>>> to make the code more readable?
>
>> ABSOLUTELY!!  Most Python programming consists of defining the functions
>> and classes needed, which definitely makes Python more readable.
>
>> No need for anyone to re-invent the
>> wheel!  ;-)
>
> I keep seeing this in the thread. Python has all this capability, yet
> it still requires a lot of fiddly code to be added to get anywhere
> near as simple as this:
>
>   read f, a, b, c
>
> And this is code that is not going to be obvious to anyone starting
> out. Even accepting that syntax limitations might require this to be
> written as:
>
>   readline(f, a, b, c)
>
> I can't see a straightforward way of making this possible while still
> keeping a, b and c simple integer, float or string types (because
> Python's reference parameters don't work quite the right way).
>
> (There is also the question of 'readline' knowing what types of values
> to read. This information would not be needed in Fortran or Basic but
> somehow needs to be supplied here, if a particular set of types is to
> imposed on the input.)
>
> In other words, it seems this particular wheel does require
> re-inventing!

It's hardly Python's problem if an engineer is worried about some VB not
being there in its current form in the future. The sample code upthread
seemed gibberish to me - anybody capable of learning *that* should be
*able* to also learn Python, and then the input parsing business is not
only simple but also flexible, as already demonstrated by others. The
following assumes that the author of the code knows the desired types,
and does not assume a working DWIM feature. I wouldn't name things quite
like that in real code.

from io import StringIO

def funcall(f, x):
return f(x)

def Input(source, *dims):
return tuple(map(funcall, dims, next(source).split()))

def Vector(dim, times):
return tuple([dim] * times)

N020SdotTXT = ''' 106 1 
8.65  0.2192347   3.33E-444 0.00516 
9 
 1 
2 1 
 3 '''

Number8 = StringIO(N020SdotTXT)

ND, NIN, NT = Input(Number8, int, int, int)
DINCOL = Input(Number8, *Vector(float, NIN))
[NINE] = Input(Number8, int)
[ONE] = Input(Number8, float)
TWO = Input(Number8, float, int)
[THREE] = Input(Number8, str)

Hash = dict

print('ND = {}, NIN = {}, NT = {}'.format(ND, NIN, NT),
  DINCOL,
  Hash(NINE = NINE, ONE = ONE, TWO = TWO, THREE = THREE),
  sep = '\n')

# Output:
# ND = 10, NIN = 6, NT = 1
# (8.65, 0.2192347, 0.000333, 44.0, 0.0051, 6.0)
# {'NINE': 9, 'TWO': (2.0, 1), 'ONE': 1.0, 'THREE': '3'}

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


Re: how to get the list form dictionary's values

2016-02-21 Thread Marko Rauhamaa
Chris Angelico :

> On Mon, Feb 22, 2016 at 1:15 AM, Ho Yeung Lee  
> wrote:
>> 0 ---> 2 --> 3--> 1 ---> 0
>> ---> 4 /
>
> So after task 2 completes, tasks 3 and 4 both become available (and
> can run in parallel), but then task 1 must wait until both have
> finished before it runs? I'm not an asyncio expert, but this sounds
> like a fairly straight-forward dependency requirement. If you were to
> implement these as four separate threads, you would have threads 3 and
> 4 raise semaphores which thread 1 blocks on; I'm sure there'll be an
> equivalent in asyncio.
>
> [...]
>
> (Can an asyncio expert tell me how to tidy this code up, please? I'm
> sure this isn't the cleanest.)

Not an expert, but this does the trick:


#!/usr/bin/env python3

import asyncio

def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(t0())

async def t0():
print("start t0")
await t2()
await asyncio.wait([ t3(), t4() ])
await t1()
print("finish t0")

async def t1():
print("start t1")
await asyncio.sleep(1)
print("finish t1")

async def t2():
print("start t2")
await asyncio.sleep(1)
print("finish t2")

async def t3():
print("start t3")
await asyncio.sleep(1)
print("finish t3")

async def t4():
print("start t4")
await asyncio.sleep(1)
print("finish t4")

if __name__ == '__main__':
main()



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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread Christian Gollwitzer

Am 21.02.16 um 14:16 schrieb BartC:

Even accepting that syntax limitations might require this to be written as:

   readline(f, a, b, c)

I can't see a straightforward way of making this possible while still
keeping a, b and c simple integer, float or string types (because
Python's reference parameters don't work quite the right way).

(There is also the question of 'readline' knowing what types of values
to read. This information would not be needed in Fortran or Basic but
somehow needs to be supplied here, if a particular set of types is to
imposed on the input.)


Are you sure that in Basic or Fortran the expected type is not supplied? 
I'm not too familiar with either, but I think that in Fortran the 
compiler deduces it from the (compile-time) static type of the variable, 
while in BASIC there used to be sigils (A$, A# etc.) to denote the type. 
A pythonic input function would look like this IMHO:


a,b,c = readline(f, int, float, str)


In other words, it seems this particular wheel does require re-inventing!


Yes, but the above seems quite trivial:

Apfelkiste:Tests chris$ cat parseline.py
def readline(f, *args):
line=f.readline().split()
return [type(x) for type,x in zip(args,line)]

with open("mydata.dat", "r") as f:
ND, NINT, NT=readline(f, int, int, int)
# next line holds NINT floats
dincol=readline(f, *NINT*[float])
# next line holds a string
text=f.readline()

print("Read: ", ND, NINT, NT)
print(dincol)
print(text)

Apfelkiste:Tests chris$ cat mydata.dat
 106 1
8.65  0.2192347   3.33E-444 0.00516
String
Apfelkiste:Tests chris$ python parseline.py
('Read: ', 10, 6, 1)
[8.65, 0.2192347, 0.000333, 44.0, 0.0051, 6.0]
String

Apfelkiste:Tests chris$

Christian

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


PyQt5 not found from Python

2016-02-21 Thread Arie van Wingerden
Python 3.5.1 installed in default Windows folder here:
  C:\Users\Arie\AppData\Local\Programs\Python\Python35-32

PyQt5 installed - it creates a folder c:\Python34

In the Python REPL i try:
   from PyQt5 import QtCore
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named 'PyQt5'

So i guess Python does not see the QT stuff.

What can i do about it?

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


Setting up/authenticating Google API?

2016-02-21 Thread Skip Montanaro
This isn't strictly a Python question, however... Once I get myself
authenticated, I intend to use the Python Google API to pump archived
mail messages from a few defunct mailing lists into Google Groups. I
thought it would be pretty straightforward, but my attempts a few
months ago were completely unsuccessful. I asked for help on the
relevant Google product forum but got zero assistance.

I'd really appreciate a little help with the setup. If anyone has had
successful experience with this, please contact me off-list. Once I
get something going, I'll write a blog post so others don't have the
same problems I have.

Thanks,

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


Python unittest2.SkipTest and general suggestion

2016-02-21 Thread Ganesh Pal
Hello team,

Please provide your guidance on how to proceed with the below test  ,
Iam on python 2.6 and Linux. I have a linitation to use python 2.6 and
unittest2


try:
import unittest2 as unittest
except ImportError:
import unittest

class isiCorruptTest(unittest.TestCase):

corrupt_baddr = {}
report=  ""
@classmethod
def setUpClass(cls):
cls.corruptSetup()

@classmethod
def corruptSetup(cls):
"""
Initial setup before unittest run
"""
logging.info("SETUP.Started !!!")
try:
logging.info("Capturing data as part of prechecks for test_xx")
capture_data()
except Exception as e:
logging.error(e)
sys.exit("Corruption injection failed...Exiting !!!")

try:
corrupt.run_scan()
except Exception as e:
logging.error(e)
raise unittest.SkipTest("Failure running Integrity Scan ")

try:
cls.report = corrupt.run_report()
except Exception as e:
logging.error(e)
raise unittest.SkipTest("Failure running Reporting Tool ")
#sys.exit(1)

logging.info("SETUP.Done !!!")

def test_04_inode(self):
""" test04:  """
logging.info("### Executing test04: ###")
self.assertTrue(corrupt.run_query(self.__class__.report,
   self.corrupt_baddr['test04']))


def main():
""" ---MAIN--- """
# both function are not shown in this code
functions = [create_logdir, create_dataset ]
for func in functions:
try:
func()
except Exception as e:
logging.error(e)
return False
unittest.main()

if __name__ == '__main__':
main()

I have the below problems while running this code:

1.  unittest.SkipTest does not the display the  exception message that
is caught.

Example : The function corrupt.run_scan() returns none and False for failures


3.  how do I the ensure that test_04 is run only it setUpClass succeeds ?

Example: Iam getting this  error message for each tests on the console.


==
ERROR: test_04_inode (__main__.isiCorruptTest)
test04: inode offset, size corruption
--
Traceback (most recent call last):
  File "c_t1.py", line 251, in test_04_inode_offset_size_corruption
self.corrupt_baddr['test04']))
KeyError: 'test04'


3.  Any other suggestion welcome


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


can try expect have if else.

2016-02-21 Thread Ganesh Pal
Hi Team,

Iam on python 2.6 , need input on the below piece of code.


EXIT_STATUS_ERROR=1

def create_dataset():
"""
 """
logging.info("Dataset create.Started !!!")
try:
if os.path.ismount("/nfs_mount"):
touch_file("inode_fixcrc.txt")
logging.info("Dataset create.Done !!!")
else:
raise Exception("/nfs_mount is not mounted. Dataset create
failed !!!")
return False
except Exception as e:
logging.error(e)
sys.stderr.write("Dataset create failed...Exiting !!!")
sys.exit(EXIT_STATUS_ERROR)
return True

1. Can we have if else with in a try except block
2. How can the above code be improved

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread BartC

On 21/02/2016 15:08, Jussi Piitulainen wrote:

BartC writes:



In other words, it seems this particular wheel does require
re-inventing!


It's hardly Python's problem if an engineer is worried about some VB not
being there in its current form in the future. The sample code upthread
seemed gibberish to me


I don't know VB6 but:

 Open "N020S.TXT" For Input As #8

 Input #8, ND, NIN, NT ' all integers

seems clear enough: read 3 integers from the text file just opened on 
channel 8, and store them in variables ND, NIN and NT.


But this is not so much to do with VB6, but with a very fundamental 
capability that seems missing in modern languages.


IIRC, the first programming exercise I ever did (in 1976 using Algol 60) 
involved reading 3 numbers from the teletype and working out if those 
could form sides of a triangle. It might have started off like this (I 
can't remember Algol 60):


  print "Type 3 numbers:"
  read a, b, c

In Basic, that last line might be:

  input a, b, c

instead (reading here as floats probably).

Now, nearly 40 years later, I don't actually know how to do that in 
Python! Sure, I can cobble something together, with all sorts of 
functions and string operations (and I would need to go and look them 
up). But it's not just /there/ already.


If you gave this a Python exercise to a class of students, you'd end up 
with 30 different solutions just for the first, easy part of the 
exercise! In fact it would be far more challenging than the triangle 
problem. That can't be right.


--
Bartc


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


Re: PyQt5 not found from Python

2016-02-21 Thread Mark Lawrence

On 21/02/2016 15:43, Arie van Wingerden wrote:

Python 3.5.1 installed in default Windows folder here:
   C:\Users\Arie\AppData\Local\Programs\Python\Python35-32

PyQt5 installed - it creates a folder c:\Python34

In the Python REPL i try:
from PyQt5 import QtCore
Traceback (most recent call last):
   File "", line 1, in 
ImportError: No module named 'PyQt5'

So i guess Python does not see the QT stuff.

What can i do about it?

TIA



There isn't a PyQt5 for Python 3.5 as I discovered about six hours ago 
when I did exactly what you've just done :)  Assuming that you get a 
version of PyQt that matches with a Python version, I'd assume that 
you'd drop it into the appropriate lib\site-packages, but I'll happily 
stand corrected on that one.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: PyQt5 not found from Python

2016-02-21 Thread Phil Thompson

On 21/02/2016 3:43 pm, Arie van Wingerden wrote:

Python 3.5.1 installed in default Windows folder here:
  C:\Users\Arie\AppData\Local\Programs\Python\Python35-32

PyQt5 installed - it creates a folder c:\Python34

In the Python REPL i try:
   from PyQt5 import QtCore
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named 'PyQt5'

So i guess Python does not see the QT stuff.

What can i do about it?

TIA


There are no PyQt installers for Python 3.5 yet. There will be when PyQt 
v5.6 is released.


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


Re: PyQt5 not found from Python

2016-02-21 Thread Arie van Wingerden
Thx. Didn't realize that!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQt5 not found from Python

2016-02-21 Thread Mark Lawrence

On 21/02/2016 16:40, Arie van Wingerden wrote:

Thx. Didn't realize that!



Please provide some context when you reply, thanks.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Python unittest2.SkipTest and general suggestion

2016-02-21 Thread Ben Finney
Ganesh Pal  writes:

> 1. unittest.SkipTest does not the display the exception message that
> is caught.

You are already supplying a custom message to ‘self.skipTest’::

except Exception as exc:
logging.error(exc)
raise unittest.SkipTest("Failure running Integrity Scan ")

So you can change that message by including the text representation of
the exception object::

except Exception as exc:
logging.error(exc)
raise unittest.SkipTest(
"Failure running Integrity Scan: {exc}".format(exc=exc))

> 3. how do I the ensure that test_04 is run only it setUpClass succeeds
> ?

If setupClass fails, why would you want to continue? Handle the error
inside the code for ‘setUpClass’.

If that's not obvious, maybe you mean something different by “only if
setUpClass succeeds”.

> 3.  Any other suggestion welcome

Please try hard to migrate to a currently-supported Python version. The
Python Software Foundation no longer supports Python 2.6, and that
translates into a justifiable desire in the Python community to also
stop supporting it.

-- 
 \ “We live in capitalism. Its power seems inescapable. So did the |
  `\   divine right of kings.” —Ursula K. LeGuin, National Book Awards |
_o__)acceptance speech, 2014-11-19 |
Ben Finney

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


Re: can try expect have if else.

2016-02-21 Thread Ben Finney
Ganesh Pal  writes:

> 1. Can we have if else with in a try except block

What result do you get when running that code? What empirical reason do
you have to think it would work or not work?

> 2. How can the above code be improved

The following sequence of statements::

raise Exception("/nfs_mount is not mounted. Dataset create failed !!!")
return False

do not make sense. The ‘return‛ statement will never be reached. So your
intent must be something other than what is expressed by that code.

-- 
 \ “Do unto others twenty-five percent better than you expect them |
  `\  to do unto you. (The twenty-five percent is [to correct] for |
_o__)error.)” —Linus Pauling's Golden Rule |
Ben Finney

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


Re: can try expect have if else.

2016-02-21 Thread Ganesh Pal
On Sun, Feb 21, 2016 at 10:37 PM, Ben Finney  wrote:

> What result do you get when running that code? What empirical reason do
> you have to think it would work or not work?

I wanted to know was is it good to have if else with in a try expect
block ,  I was checking more from the programming perspective  and if
I need to avoid it and if its recommended

>> 2. How can the above code be improved
>
> The following sequence of statements::
>
> raise Exception("/nfs_mount is not mounted. Dataset create failed !!!")
> return False
>
> do not make sense. The ‘return‛ statement will never be reached. So your
> intent must be something other than what is expressed by that code.
>

 I was using it with create_data function in the below code .  If
create_dataset failed the exception would be caught  , I think you are
right I need not worry about returning False

functions = [create_logdir, create_dataset]
for func in functions:
try:
func()
except Exception as e:
logging.error(e)
return False

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


Re: show instant data on webpage

2016-02-21 Thread mustang



You need free and private?  The price is low -- if this is a business why
not pay?  If not a business, why private?


it's not business it's like a school project, so no money :D


There is another charting library called pygal which is great.  It can
produce output to .svg file format or .png.  You could distribute the files
which will display in a browser.  Or you could build them into web pages if
you are so inclined to build a website.  It seems that isn't what you want
to do.  You could also upload images to some free image site. Photobucket
supports .png images.  pygal can create .png images




ok thanks.

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


SQLite

2016-02-21 Thread Klaus Jantzen
   Hello,

   I have downloaded Python3.5.1 as .targz, compiled it(configure, make,...)
   and it works
   (under Debian Wheezy AMD64) up to the moment I wanted to use SQLite.

   I get the following message:
   ===
   jantzen@PC4:~$ python
   Python 3.5.0 (default, Dec  2 2015, 14:16:16)
   [GCC 4.7.2] on linux
   Type "help", "copyright", "credits" or "license" for more information.
   >>> import sqlite3
   Traceback (most recent call last):
     File "", line 1, in 
     File "/usr/local/lib/python3.5/sqlite3/__init__.py", line 23, in
   
       from sqlite3.dbapi2 import *
     File "/usr/local/lib/python3.5/sqlite3/dbapi2.py", line 27, in 
       from _sqlite3 import *
   ImportError: No module named '_sqlite3'
   ===

   Obviously something is missing.
   How do I solve the problem? Where do I find this module?

   Thanks for a hint.
   --

   K.D.J.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python unittest2.SkipTest and general suggestion

2016-02-21 Thread Ganesh Pal
On Sun, Feb 21, 2016 at 10:33 PM, Ben Finney  wrote:

> You are already supplying a custom message to ‘self.skipTest’::
>
> except Exception as exc:
> logging.error(exc)
> raise unittest.SkipTest("Failure running Integrity Scan ")
>
> So you can change that message by including the text representation of
> the exception object::
>
> except Exception as exc:
> logging.error(exc)
> raise unittest.SkipTest(
> "Failure running Integrity Scan: {exc}".format(exc=exc))
>


Thank you for the pointers , but I modified my code to use raise
instead of exception , just wondering how will I display the message
with the below code ,

Sample code :

import os
try:
import unittest2 as unittest
except ImportError:
import unittest

class MyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
#x = False
x = None
if not x:
raise unittest.SkipTest(
"class setup failed")

def test_one(self):
print "test_one"

def test_two(self):
print "test_two"

if __name__ == "__main__":
unittest.main()

output:

gpal-3c6dc81-1# python c_4.py
s
--
Ran 0 tests in 0.000s

OK (skipped=1)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread Tim Chase
On 2016-02-21 13:16, BartC wrote:
> > No need for anyone to re-invent the
> > wheel!  ;-)
> 
> I keep seeing this in the thread. Python has all this capability,
> yet it still requires a lot of fiddly code to be added to get
> anywhere near as simple as this:
> 
>read f, a, b, c
> 
> And this is code that is not going to be obvious to anyone starting
> out. Even accepting that syntax limitations might require this to
> be written as:
> 
>readline(f, a, b, c)

Well, if you know what the line is going to contain, that can be
written as

  a, b, c = f.readline().split()

> I can't see a straightforward way of making this possible while
> still keeping a, b and c simple integer, float or string types
> (because Python's reference parameters don't work quite the right
> way).

However, that does give you byte-strings since that's what comes out
of files.  If you know they're ints, you can force that:

  a, b, c = map(int, f.readline().split())

> (There is also the question of 'readline' knowing what types of
> values to read. This information would not be needed in Fortran or
> Basic but somehow needs to be supplied here, if a particular set of
> types is to imposed on the input.)
> 
> In other words, it seems this particular wheel does require
> re-inventing!

In both Fortran & BASIC, you specify that information somewhere as
well.  However, it sounds like you define those at the
variable-definition level (it's been over a decade since I done any
BASIC and far longer since I've even touched any Fortran, so forgive
me if I'm a tad rusty) instead of where its read from the file.

-tkc






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


Re: can try expect have if else.

2016-02-21 Thread Ian Kelly
On Feb 21, 2016 9:13 AM, "Ganesh Pal"  wrote:
>
> Hi Team,
>
> Iam on python 2.6 , need input on the below piece of code.

Python 2.6 isn't supported and hasn't been since October 2013. Is there
something preventing you from upgrading to 2.7?

> EXIT_STATUS_ERROR=1
>
> def create_dataset():
> """
>  """

Empty docstring is pointless.

> logging.info("Dataset create.Started !!!")

This is just a pet peeve of mine, but do info-level log messages really
need triple exclamation marks?

> try:
> if os.path.ismount("/nfs_mount"):
> touch_file("inode_fixcrc.txt")

Is this file really meant to be created in the current working directory,
or is it supposed to be inside the /nfs_mount?

> logging.info("Dataset create.Done !!!")
> else:
> raise Exception("/nfs_mount is not mounted. Dataset create
> failed !!!")
> return False
> except Exception as e:
> logging.error(e)
> sys.stderr.write("Dataset create failed...Exiting !!!")
> sys.exit(EXIT_STATUS_ERROR)
> return True
>
> 1. Can we have if else with in a try except block

Yes, of course.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Make a unique filesystem path, without creating the file

2016-02-21 Thread Cameron Simpson

On 16Feb2016 19:24, Alan Bawden  wrote:

Ben Finney  writes:

Cameron Simpson  writes:

I've been watching this for a few days, and am struggling to
understand your use case.


Yes, you're not alone. This surprises me, which is why I'm persisting.


Can you elaborate with a concrete example and its purpose which would
work with a mktemp-ish official function?


An example::


Let me present another example that might strike some as more
straightforward.

If I want to create a temporary file, I can call mkstemp().
If I want to create a temporary directory, I can call mkdtemp().

Suppose that instead of a file or a directory, I want a FIFO or a
socket.

A FIFO is created by passing a pathname to os.mkfifo().  A socket is
created by passing a pathname to an AF_UNIX socket's bind() method.  In
both cases, the pathname must not name anything yet (not even a symbolic
link), otherwise the call will fail.

So in the FIFO case, I might write something like the following:

   def make_temp_fifo(mode=0o600):
   while True:
   path = tempfile.mktemp()
   try:
   os.mkfifo(path, mode=mode)
   except FileExistsError:
   pass
   else:
   return path

mktemp() is convenient here, because I don't have to worry about whether
I should be using "/tmp" or "/var/tmp" or "c:\temp", or whether the
TMPDIR environment variable is set, or whether I have permission to
create entries in those directories.  It just gives me a pathname
without making me think about the rest of that stuff.


Yes, that is highly desirable.


Yes, I have to
defend against the possibility that somebody else creates something with
the same name first, but as you can see, I did that, and it wasn't
rocket science.

So is there something wrong with the above code?  Other than the fact
that the documentation says something scary about mktemp()?


Well, it has a few shortcomings.

It relies on mkfifo reliably failing if the name exists. It shounds like mkfifo 
is reliable this way, but I can imagine analogous use cases without such a 
convenient core action, and your code only avoids mktemp's security issue 
_because_ mkfifo has that fortuitous aspect.



It looks to me like mktemp() provides some real utility, packaged up in
a way that is orthogonal to the type of file system entry I want to
create, the permissions I want to give to that entry, and the mode I
want use to open it.  It looks like a useful, albeit low-level,
primitive that it is perfectly reasonable for the tempfile module to
supply.


Secondly, why is your example better than::

 os.mkfifo(os.path.join(mkdtemp(), 'myfifo'))

On that basis, this example doesn't present a use case what can't be addressed 
by mkstemp or mkdtemp.


By contrast, Ben's example does look like it needs something like mktemp.


And yet the documentation condemns it as "deprecated", and tells me I
should use mkstemp() instead.


You _do_ understand the security issue, yes? I sure looked like you did, until 
here. 


(As if that would be of any use in the
situation above!)  It looks like anxiety that some people might use
mktemp() in a stupid way has caused an over-reaction.


No, it is anxiety that mktemp's _normal_ use is inherently unsafe.


Let the
documentation warn about the problem and point to prepackaged solutions
in the common cases of making files and directories, but I see no good
reason to deprecate this useful utility.


I think it is like C's gets() function (albeit not as dangerous). It really 
shouldn't be used.


One of the things about mktemp() is its raciness, which is the core of the 
security issue. People look at the term "security issue" and think "Ah, it can 
be attacked." But the flipside is that it is simply unreliable. Its normal use 
was to make an ordinary temp file. Consider the case where two instances of the 
same task are running at the same time, doing that. They can easily, by 
accident, end us using the same scratch file!


This is by no means unlikely; any shell script running tasks in parallel can 
arrange it, any procmail script filing a message with a "copy" rule (which 
causes procmail simply to fork and proceed), etc.


This is neither weird nor even unlikely which is why kmtemp is strongly 
discouraged - naive (and standard) use is not safe.


That you have contrived a use case where you can _carefully_ use mktemp in 
safety in no way makes mktemp recommendable. In fact your use case isn't safe, 
because _another_ task using mktemp in conflict as a plain old temporary file 
may grab your fifo.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


RE: SQLite

2016-02-21 Thread Albert-Jan Roskam
(Sorry for top posting)

IIRC, you have to do
sudo apt-get install build-essential python-dev
... then re-compile python

> To: [email protected]
> From: [email protected]
> Subject: SQLite
> Date: Sun, 21 Feb 2016 18:11:18 +0100
> 
>Hello,
> 
>I have downloaded Python3.5.1 as .targz, compiled it(configure, make,...)
>and it works
>(under Debian Wheezy AMD64) up to the moment I wanted to use SQLite.
> 
>I get the following message:
>===
>jantzen@PC4:~$ python
>Python 3.5.0 (default, Dec  2 2015, 14:16:16)
>[GCC 4.7.2] on linux
>Type "help", "copyright", "credits" or "license" for more information.
>>>> import sqlite3
>Traceback (most recent call last):
>  File "", line 1, in 
>  File "/usr/local/lib/python3.5/sqlite3/__init__.py", line 23, in
>
>from sqlite3.dbapi2 import *
>  File "/usr/local/lib/python3.5/sqlite3/dbapi2.py", line 27, in 
>from _sqlite3 import *
>ImportError: No module named '_sqlite3'
>===
> 
>Obviously something is missing.
>How do I solve the problem? Where do I find this module?
> 
>Thanks for a hint.
>--
> 
>K.D.J.
> -- 
> https://mail.python.org/mailman/listinfo/python-list
  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread Jussi Piitulainen
BartC writes:

> But this is not so much to do with VB6, but with a very fundamental
> capability that seems missing in modern languages.

All that's missing is a minor convenience that turns out to be mainly
awkward. Not at all fundamental.

The capability of parsing simple input formats is easily composed of
more generally useful components that are available. As demonstrated in
this thread.

I get a bit carried away about input() below, but really, it's the
abstraction and composition of programs that is fundamental and
exciting, Python has *that*, and that makes it possible to define the
desired input parsers in a couple of lines. Simply.

> IIRC, the first programming exercise I ever did (in 1976 using Algol
> 60) involved reading 3 numbers from the teletype and working out if
> those could form sides of a triangle.

That was a lousy user interface even then - an inflexible user
interaction without even a possibility of handling errors interactively?
Command line arguments would have been better (if available, that is).

In Python, use the interactive loop instead (or command line arguments,
of course, or input(), and I think it's slightly simpler to use input()
three times than instruct the user about how to separate the three
numbers).

> It might have started off like this (I can't remember Algol 60):
>
>   print "Type 3 numbers:"
>   read a, b, c
>
> In Basic, that last line might be:
>
>   input a, b, c
>
> instead (reading here as floats probably).
>
> Now, nearly 40 years later, I don't actually know how to do that in
> Python! Sure, I can cobble something together, with all sorts of
> functions and string operations (and I would need to go and look them
> up). But it's not just /there/ already.

It seems you'd need to look them up in Algol 60 and Basic, too. Nothing
wrong with that.

You can ask for a line of input with input('>>> ') in Python 3. The
methods of parsing simple input formats, such as those in this thread,
with or without validation, are generally useful, composable, flexible,
and not at all difficult. You'll get far by line.split(), splitting at
any amount of whitespace by default (note that the .strip() in the
line.strip().split() that someone posted is redundant).

It's *good* to be able to cobble together a simple one-liner that does
what you want with fundamental, reusable components. Or a three-liner if
you *want* something more complex. Or a page of code to fake something
that is really AI-complete, if *that's* what you want. But mainly I mean
that the present problem is just trivial, and what do you do with the
Basic command if you have a slightly different input format - does it
scale at all? If there is extra text on the line before the numbers? If
the numbers are separated by commas, or semicolons?

> If you gave this a Python exercise to a class of students, you'd end
> up with 30 different solutions just for the first, easy part of the
> exercise! In fact it would be far more challenging than the triangle
> problem. That can't be right.

You mean those students who have never even started a program from a
command line? Whose first command-line interface ever is the Python
interactive loop in IDLE or some other such integrated environment where
they still don't learn to start a program from a command line? Those
students?

Well, why would they write code that asks for interactive input at all?
They can simply call their triangle-testing function in the Python
interactive loop and specify the integers as arguments:

>>> def istriangle(*threeintegers):
a,b,c = sorted(threeintegers)
return a*a + b*b == c*c

>>> istriangle(3,4,5)
True
>>> istriangle(3,1,4)
False

The development environment probably lets them send their code to the
interaction window from an editor window. Some might be able to learn
the advanced techniques required to import a program file into an
interactive session launched in a terminal window.

You insist on them asking for input anyway? How about telling them that
they can get a line of input (if they have some sort of console
available, I suppose) by calling, er, input, and the simplest way to
parse a string, call it s, as an integer is int(s)? (Tell them that if
they just guess that the input method might be called input they can get
their guess confirmed by trying help(input). Another useful skill.)

>>> def awkward():
a = int(input('int> '))
b = int(input('int> '))
c = int(input('int> '))
istriangle(a, b, c)
 
>>> awkward()
int> 3
int> 1
int> 4
>>> # oops

>>> def awkward():
a = int(input('int> '))
b = int(input('int> '))
c = int(input('int> '))
return istriangle(a, b, c)
 
>>> awkward()
int> 5
int> 4
int> 3
True
>>> 

Point out that it's a good idea to have a separate function to check for
triangularity of the triple of numbers: it'll be composable with other,
better sources of such triples (web form? command line arguments? random
numbers? loop over a million rando

Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-21 Thread BartC

On 21/02/2016 21:52, Jussi Piitulainen wrote:

BartC writes:


But this is not so much to do with VB6, but with a very fundamental
capability that seems missing in modern languages.


All that's missing is a minor convenience that turns out to be mainly
awkward. Not at all fundamental.


It /is/ fundamental because it mimics how humans interact:

"Give me 3 numbers:"

"OK: ten, twenty and twenty-nine."

"Yeah, they'd make a triangle."


The capability of parsing simple input formats is easily composed of
more generally useful components that are available. As demonstrated in
this thread.


Yes, by having a box of parts you first have to figure out how to put 
together!



IIRC, the first programming exercise I ever did (in 1976 using Algol
60) involved reading 3 numbers from the teletype and working out if
those could form sides of a triangle.



That was a lousy user interface even then - an inflexible user
interaction without even a possibility of handling errors interactively?
Command line arguments would have been better (if available, that is).


The big deal about that kind of interface was it that it /was/ 
interactive (compared with batch processing or job control or whatever. 
I remember using punched cards; those certainly weren't).


Command line arguments are not interactive. If the name of the program 
is Triangle, and someone types:


>Triangle

the probably nothing happens. Or it generates an error message. Or it 
appears to hang.



In Python, use the interactive loop instead (or command line arguments,
of course, or input(), and I think it's slightly simpler to use input()
three times than instruct the user about how to separate the three
numbers).


Basics also used to use interactive loops. Separating the numbers I 
don't think has ever been a big problem. Obviously you can't type ten, 
twenty and thirty as 102030, but will need to use white-space or 
punctuation. It doesn't take long to figure out! (And how do you 
separate command-line arguments? Have you even thought about it?)



Now, nearly 40 years later, I don't actually know how to do that in
Python! Sure, I can cobble something together, with all sorts of
functions and string operations (and I would need to go and look them
up). But it's not just /there/ already.


It seems you'd need to look them up in Algol 60 and Basic, too. Nothing
wrong with that.


Yes, and it would say use 'readln' or 'input' or whatever. In Python, 
I'd get two-inch-thick manual full of library functions and modules I 
can use to /implement/ 'readln' or 'input'!



It's *good* to be able to cobble together a simple one-liner that does
what you want with fundamental, reusable components. Or a three-liner if
you *want* something more complex.


But this is advanced stuff for a beginner. (I'm not a beginner and it's 
advanced for /me/! Well, more of a nuisance when I want to quickly do X 
but first need to figure out Y, some input routine.)


 Or a page of code to fake something

that is really AI-complete, if *that's* what you want. But mainly I mean
that the present problem is just trivial, and what do you do with the
Basic command if you have a slightly different input format - does it
scale at all? If there is extra text on the line before the numbers? If
the numbers are separated by commas, or semicolons?


I don't know the details of how Basic does it. But it seems to allow any 
reasonable separator, while asking for more input than is provided on 
the line sets those extra variables to 0 or "".



If you gave this a Python exercise to a class of students, you'd end
up with 30 different solutions just for the first, easy part of the
exercise!



Well, why would they write code that asks for interactive input at all?
They can simply call their triangle-testing function in the Python
interactive loop and specify the integers as arguments:


def istriangle(*threeintegers):

 a,b,c = sorted(threeintegers)
 return a*a + b*b == c*c


(That detects right-angled triangles. I think 'return a+b>c' is the 
correct test for any triangle. It becomes trivial when you have sort 
available, but that's part of the point of the exercise.)



istriangle(3,4,5)

True

istriangle(3,1,4)

False


Yes, this is a good next step, to separate the logic from the job of 
acquiring the data (and to learn about with subroutines or functions).


But this way, you're putting off the job of requesting interactive data 
from a user. If A is the chap writing the program and using the tools, 
he might want B to be the one running the program and entering the data. 
B won't be running the interactive loop; he won't even know what 
language it's in. (And the OP wants B to run an EXE.)



And then there are all the common data sources and formats (CSV, JSON,
XML, ...) that change the game altogether. All the functions and
expression types used to parse the simple input lines in this thread are
still useful, but what use is that very special Basic input command now?
None wh

Re: SQLite

2016-02-21 Thread Chris Angelico
On Mon, Feb 22, 2016 at 8:37 AM, Albert-Jan Roskam
 wrote:
> IIRC, you have to do
> sudo apt-get install build-essential python-dev
> ... then re-compile python

That may well work, but it's probably easier to work this way:

sudo apt-get build-dep python3

That should grab all the compilation dependencies of the python3
package, which on Wheezy is a 3.2 IIRC. The deps haven't changed since
then AFAIK.

When you build, you should get a summary at the end that tells you
about any modules that couldn't be built. The most common reason for
that is missing deps. If you still have any after running the above,
post here and we may be able to more directly advise.

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