Non-GUI, single processort inter process massaging - how?

2018-07-21 Thread Chris Green
I have a need to allow short-lived 'client' processes to interrogate a
single long-lived 'server' process on a small system (specifically a
BeagleBone Black).

The server process reads values from external hardware and this
needs to be done by a single process to ensure that it works as
intended and to allow simple smoothing algorithms to be applied.
Using multiple processes to do this would be difficult.

I want to be able to interrogate the server process from several
client processes, some will interrogate it multiple times, others once
only.  They are mostly (all?) run from the command line (bash).

There is no GUI and all these processes will always be on a single
system.  

A single multi-threaded process doesn't really work because I don't
see how one could then run something at command line which could get
values from the server process.

So - what's the best approach to this?  I've done some searching and
most/many of the solutions seem rather heavyweight for my needs. Am I
overlooking something obvious or should I try rethinking the original
requirement and look for another approach?


(currently each 'client' simply reads the hardware directly using a
Python module I have written, however this hits the hardware more than
necessary and makes smoothing and such difficul)

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try except inside a with open

2018-07-21 Thread Ganesh Pal
>
>
>
> (1) Since this function always returns True (if it returns at all), what
> is the point? There's no point checking the return result, since it's
> always true, so why bother returning anything?
>
>

If  I don't return anything from a function it returns None.   But would it
be better if for the  function  i.e modify_various_line(f) to  atleast catch
or handle exceptions and log it for debugging purpose

Example:

def modify_various_line(f):
""" Try modifiying various line """
try:
f.write('0123456789abcdef')
f.seek(5) # Go to the 6th byte in the file
print f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
print f.read(1)
f.write('END')
except IOError as e:
   logging.error("Error: got %s" , % (str(e)))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try except inside a with open

2018-07-21 Thread Cameron Simpson
Please try to preserve the attribution lines of previous authors. The inner 
quote below comes from Steven D'Aprano.


On 21Jul2018 15:13, Ganesh Pal  wrote:

(1) Since this function always returns True (if it returns at all), what
is the point? There's no point checking the return result, since it's
always true, so why bother returning anything?


If  I don't return anything from a function it returns None.   But would it
be better if for the  function  i.e modify_various_line(f) to  atleast catch
or handle exceptions and log it for debugging purpose


Usually not.

Problems with this approach (catches and logging, and _concealing_ the 
exception from the caller) include:


1: the primary one is: if you do this, the caller will never know that anything 
went wrong


2: there isn't necessarily any logging setup anyway - small function should not 
need to know or care, otherwise they're hard to test and may make a lot of 
unwanted noise


Most functions do not know the larger programme context - it is therefore not 
possible to decide how to handle all exceptions. So unless the exception is 
anticipated for some specific situation, it is better to let it excape for the 
caller to handle (or not).


Look at your example function:


Example:

def modify_various_line(f):
   """ Try modifiying various line """
   try:
   f.write('0123456789abcdef')
   f.seek(5) # Go to the 6th byte in the file
   print f.read(1)
   f.seek(-3, 2) # Go to the 3rd byte before the end
   print f.read(1)
   f.write('END')
   except IOError as e:
  logging.error("Error: got %s" , % (str(e)))


This function returns None regardless of success or failure. Generally for a 
function like this, which doesn't return a "result", you want it to return on 
success and raise an exception on failure. In that way, the caller can presume 
things are good if no exception occurred.


Here you print an error message to the log and return None anyway.

Firstly, your error message has no context: there's just an IOError in the log, 
so nobody can review the log and know what the error is associate with. If the 
IOError had been allowed to get out, the caller could have responded 
appropriately (or not, letting the exception further out to someone who can, or 
aborting the programme if nobody deals with it). This isn't as bad as it 
sounds; that abort is a symptom of a genuinely unanticipated error, which 
should be either understood properly and handled, or the invoker of the program 
should respond to its termination. In a sense, your whole programme is itself a 
function - if it didn't work, the person invoking it needs to find out.


Secondly, because you catch the error, the caller has no way to know the 
function did not accomplish what the caller expected. That is "silent failure",

and generally a bad thing.

Consider this trite function:

 def get_colour(thing, default='black'):
   try:
 colour = thing.colour
   except AttributeError:
 colour = default
   return colour

Here we handle the case where a thing has no .colour attribute and return a 
default. The function is designed for this, and has scope for the caller to 
specify the default.


The general rule in Python is: only catch an exception if you know exactly what 
to do with it, and your function will complete with a _correct_ result if you 
do it.


Conversely, _don't_ try to handle any other situation. (This makes your task 
easier, too!)


Here's an example:

 import errno
 ...
 # clean up a file...
 try:
   os.remove(filename)
 except OSError as e:
   if e.errno == errno.ENOENT:
 # it is ok if the file is already gone
 pass
   else:
 raise

Here we're catching all OSErrors, but only handling the specific situation we 
understand (the file doesn't exist, and in this case that is possible and 
normal). If there was any other kind of OSError (eg a permission error or 
anything else really - it is all unknown), we reraise the original exception.


There are any number of reasons that things can go wrong, including the code 
_calling_ your function asking for the wrong thing. Letting the exception out 
lets these situations get debugged.


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


Better way / regex to extract values form a dictionary

2018-07-21 Thread Ganesh Pal
I have one of the dictionary values in the below format

'/usr/local/ABCD/EDF/ASASAS/GTH/HELLO/MELLO/test04_Failures.log'
'/usr/local/ABCD/EDF/GTH/HEL/OOLO/MELLO/test02_Failures.log'
'/usr/local/ABCD/EDF/GTH/BEL/LO/MELLO/test03_Failures.log'

I need to extract the file name in the path example, say test04_Failure.log
and testcase no i.e test04


Here is my solutions:

gpal-cwerzvd-1# vi filename.py
import re

Common_dict = {}
Common_dict['filename'] =
'/usr/local/ABCD/EDF/GTH/HELLO/MELLO/test04_Failures.log'

def return_filename_test_case(filepath):
if filepath:
   filename = re.findall(r'(test\d{1,4}_\S+)', filepath)
if filename:
   testcase = re.findall(r'(test\d{1,4})', ''.join(filename))

return filename, testcase


if Common_dict['filename']:
   path = Common_dict['filename']
   fname, testcase = return_filename_test_case(path)
   print fname, testcase


op:
qerzvd-1# python filename.py
['test04_Failures.log']
['test04']


Please suggest how can this code can be optimized  further looks messy ,
what would be your one liner or a simple solution to return both test-case
no and filename

I am on Python 2.7 and Linux


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


Re: Better way / regex to extract values form a dictionary

2018-07-21 Thread Paul Moore
def return_filename_test_case(filepath):
filename = os.path.basename(filepath)
testcase = filename.partition('_')[0]
return filename, testcase

On 21 July 2018 at 12:37, Ganesh Pal  wrote:
> I have one of the dictionary values in the below format
>
> '/usr/local/ABCD/EDF/ASASAS/GTH/HELLO/MELLO/test04_Failures.log'
> '/usr/local/ABCD/EDF/GTH/HEL/OOLO/MELLO/test02_Failures.log'
> '/usr/local/ABCD/EDF/GTH/BEL/LO/MELLO/test03_Failures.log'
>
> I need to extract the file name in the path example, say test04_Failure.log
> and testcase no i.e test04
>
>
> Here is my solutions:
>
> gpal-cwerzvd-1# vi filename.py
> import re
>
> Common_dict = {}
> Common_dict['filename'] =
> '/usr/local/ABCD/EDF/GTH/HELLO/MELLO/test04_Failures.log'
>
> def return_filename_test_case(filepath):
> if filepath:
>filename = re.findall(r'(test\d{1,4}_\S+)', filepath)
> if filename:
>testcase = re.findall(r'(test\d{1,4})', ''.join(filename))
>
> return filename, testcase
>
>
> if Common_dict['filename']:
>path = Common_dict['filename']
>fname, testcase = return_filename_test_case(path)
>print fname, testcase
>
>
> op:
> qerzvd-1# python filename.py
> ['test04_Failures.log']
> ['test04']
>
>
> Please suggest how can this code can be optimized  further looks messy ,
> what would be your one liner or a simple solution to return both test-case
> no and filename
>
> I am on Python 2.7 and Linux
>
>
> Regards,
> Ganesh
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Better way / regex to extract values form a dictionary

2018-07-21 Thread Steven D'Aprano
On Sat, 21 Jul 2018 17:07:04 +0530, Ganesh Pal wrote:

> I have one of the dictionary values in the below format
> 
> '/usr/local/ABCD/EDF/ASASAS/GTH/HELLO/MELLO/test04_Failures.log'
> '/usr/local/ABCD/EDF/GTH/HEL/OOLO/MELLO/test02_Failures.log'
> '/usr/local/ABCD/EDF/GTH/BEL/LO/MELLO/test03_Failures.log'
> 
> I need to extract the file name in the path example, say
> test04_Failure.log and testcase no i.e test04

The dictionary is irrelevant to your question. It doesn't matter whether 
the path came from a dict, a list, read directly from stdin, an 
environment variable, extracted from a CSV file, or plucked directly from 
outer space by the programmer. The process remains the same regardless of 
where the path came from.


import os
path = '/usr/local/ABCD/EDF/ASASAS/GTH/HELLO/MELLO/test04_Failures.log'

filename = os.path.basename(path)
print filename
# prints 'test04_Failures.log'

testcase, remaining_junk = filename.split('_', 1)
print testcase
# prints 'test04'



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: Better way / regex to extract values form a dictionary

2018-07-21 Thread Ganesh Pal
> The dictionary is irrelevant to your question. It doesn't matter whether
> the path came from a dict, a list, read directly from stdin, an
> environment variable, extracted from a CSV file, or plucked directly from
> outer space by the programmer. The process remains the same regardless of
> where the path came from.
>


Thanks I was ignorant about this  , your solution looks cool .  One last
question , does it makes sense to check if the values are not none ( If I
plan to use the value for next computation )

 if not all(filename, testcase):
   raise ValueError("Error getting filename or testcase no")


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


Re: Non-GUI, single processort inter process massaging - how?

2018-07-21 Thread Steven D'Aprano
On Sat, 21 Jul 2018 09:07:23 +0100, Chris Green wrote:

[...]
> I want to be able to interrogate the server process from several client
> processes, some will interrogate it multiple times, others once only. 
> They are mostly (all?) run from the command line (bash).


This sounds like a good approach for signals. Your server script sets up 
one or more callbacks that print the desired information to stdout, or 
writes it to a file, whichever is more convenient, and then you send the 
appropriate signal to the server process from the client processes.

At the bash command line, you use the kill command: see `man kill` for 
details.


Here's a tiny demo:

# === cut ===

import signal, os, time
state = 0

def sig1(signum, stack):
print(time.strftime('it is %H:%m:%S'))

def sig2(signum, stack):
print("Current state:", stack.f_globals['state'])

# Register signal handlers
signal.signal(signal.SIGUSR1, sig1)
signal.signal(signal.SIGUSR2, sig2)

# Print the process ID.
print('My PID is:', os.getpid())

while True:
state += 1
time.sleep(0.2)

# === cut ===


Run that in one terminal, and the first thing it does is print the 
process ID. Let's say it prints 12345, over in another terminal, you can 
run:

kill -USR1 12345
kill -USR2 12345

to send the appropriate signals.

To do this programmatically from another Python script, use the os.kill() 
function.


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

https://pymotw.com/3/signal/




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: Cookies not showing up in environ

2018-07-21 Thread Jon Ribbens
On 2018-07-20, abc abc  wrote:
> Well, I'm so messed up between so many sources and tutorials I don't
> know which way is up. 

I think one of the main issues is that you don't seem to have decided
whether you're writing a WSGI application or a Django application.

WSGI:

def application(environ, start_response):
start_response('200 OK',
   [('Content-Type', 'text/plain; charset=utf-8')])
return [environ.get('HTTP_COOKIE', '').encode('utf-8')]


Django:

views.py:

from django.http import HttpResponse

def cookies(request):
return HttpResponse(repr(request.COOKIES),
'text/plain; charset=utf-8')

urls.py:

from django.urls import path

from . import views

urlpatterns = [
path('cookies', views.cookies),
]

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


pattern block expression matching

2018-07-21 Thread aldi . kraja
Hi,
I have a long text, which tells me which files from a database were downloaded 
and which ones failed. The pattern is as follows (at the end of this post). 
Wrote a tiny program, but still is raw. I want to find term "ERROR" and go 5 
lines above and get the name with suffix XPT, in this first case DRXIFF_F.XPT, 
but it changes in other cases to some other name with suffix XPT. Thanks, Aldi

# reading errors from a file txt
import re
with open('nohup.out', 'r') as fh:
  lines = fh.readlines()
  for line in lines:
  m1 = re.search("XPT", line)
  m2 = re.search('ERROR', line)
  if m1:
print(line)
  if m2:
print(line)







--2018-07-14 21:26:45--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXIFF_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:46 ERROR 404: Not Found.

--2018-07-14 21:26:46--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXTOT_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:46 ERROR 404: Not Found.

--2018-07-14 21:26:46--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXFMT_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:46 ERROR 404: Not Found.

--2018-07-14 21:26:46--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DSQ1_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:47 ERROR 404: Not Found.

--2018-07-14 21:26:47--  https://wwwn.cdc.gov/Nchs/Nhanes/1999-2000/DSII.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 56060880 (53M) [application/octet-stream]
Saving to: ‘DSII.XPT’
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Non-GUI, single processort inter process massaging - how?

2018-07-21 Thread Chris Green
Steven D'Aprano  wrote:
> On Sat, 21 Jul 2018 09:07:23 +0100, Chris Green wrote:
> 
> [...]
> > I want to be able to interrogate the server process from several client
> > processes, some will interrogate it multiple times, others once only. 
> > They are mostly (all?) run from the command line (bash).
> 
> 
> This sounds like a good approach for signals. Your server script sets up 
> one or more callbacks that print the desired information to stdout, or 
> writes it to a file, whichever is more convenient, and then you send the 
> appropriate signal to the server process from the client processes.
> 
[snip useful sample scripts]

Yes, maybe, though I was hoping for something a bit more sophisticated.

At the moment it's the 'client' processes which manage the output side
of things, pushing it across to the 'server' would mean that the
client does nothing except send a signal.  As the outputs are to quite
a variety of things (e.g. terminal  screen, serial connection, LCD
display) this would push a lot of code to the server which currently
is quite nicely separated into client modules.

Communicating by file is a possible approach I had considered though,
the server can do its smoothing etc. of results and write them to a
file which is then read as required by the client processes.  The only
issue then is the need for some sort of locking as one doesn't want
the client to read while the server is writing.  One could overcome
this by using a temporary file though, mv/rename is supposed to be
atomic.

Going back to my original request the clients don't really need to be
able to 'interrogate' the server, they just need to be able to access
results produced by the server.  So maybe simply having the server
write the values to file is all that's really needed.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pattern block expression matching

2018-07-21 Thread MRAB

On 2018-07-21 15:20, aldi.kr...@gmail.com wrote:

Hi,
I have a long text, which tells me which files from a database were downloaded and which 
ones failed. The pattern is as follows (at the end of this post). Wrote a tiny program, 
but still is raw. I want to find term "ERROR" and go 5 lines above and get the 
name with suffix XPT, in this first case DRXIFF_F.XPT, but it changes in other cases to 
some other name with suffix XPT. Thanks, Aldi

# reading errors from a file txt
import re
with open('nohup.out', 'r') as fh:
   lines = fh.readlines()
   for line in lines:
   m1 = re.search("XPT", line)
   m2 = re.search('ERROR', line)
   if m1:
 print(line)
   if m2:
 print(line)

Firstly, you don't need regex for something has simple has checking for 
the presence of a string.


Secondly, I think it's 4 lines above, not 5.

'enumerate' comes in useful here:

with open('nohup.out', 'r') as fh:
lines = fh.readlines()
for i, line in enumerate(lines):
if 'ERROR' in line:
print(line)
print(lines[i - 4])



--2018-07-14 21:26:45--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXIFF_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:46 ERROR 404: Not Found.

--2018-07-14 21:26:46--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXTOT_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:46 ERROR 404: Not Found.

--2018-07-14 21:26:46--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXFMT_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:46 ERROR 404: Not Found.

--2018-07-14 21:26:46--  https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DSQ1_F.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2018-07-14 21:26:47 ERROR 404: Not Found.

--2018-07-14 21:26:47--  https://wwwn.cdc.gov/Nchs/Nhanes/1999-2000/DSII.XPT
Resolving wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39
Connecting to wwwn.cdc.gov (wwwn.cdc.gov)|198.246.102.39|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 56060880 (53M) [application/octet-stream]
Saving to: ‘DSII.XPT’



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


Re: pattern block expression matching

2018-07-21 Thread Peter Otten
MRAB wrote:

> On 2018-07-21 15:20, aldi.kr...@gmail.com wrote:
>> Hi,
>> I have a long text, which tells me which files from a database were
>> downloaded and which ones failed. The pattern is as follows (at the end
>> of this post). Wrote a tiny program, but still is raw. I want to find
>> term "ERROR" and go 5 lines above and get the name with suffix XPT, in
>> this first case DRXIFF_F.XPT, but it changes in other cases to some other
>> name with suffix XPT. Thanks, Aldi
>> 
>> # reading errors from a file txt
>> import re
>> with open('nohup.out', 'r') as fh:
>>lines = fh.readlines()
>>for line in lines:
>>m1 = re.search("XPT", line)
>>m2 = re.search('ERROR', line)
>>if m1:
>>  print(line)
>>if m2:
>>  print(line)
>> 
> Firstly, you don't need regex for something has simple has checking for
> the presence of a string.
> 
> Secondly, I think it's 4 lines above, not 5.
> 
> 'enumerate' comes in useful here:
> 
> with open('nohup.out', 'r') as fh:
>  lines = fh.readlines()
>  for i, line in enumerate(lines):
>  if 'ERROR' in line:
>  print(line)
>  print(lines[i - 4])

Here's an alternative that works when the file is huge, and reading it into 
memory is impractical:

import itertools

def get_url(line):
return line.rsplit(None, 1)[-1]

def pairs(lines, step=4):
a, b = itertools.tee(f)
return zip(a, itertools.islice(b, step, None))

with open("nohup.out") as f:
for s, t in pairs(f, 4):
if "ERROR" in t:
assert "XPT" in s
print(get_url(s))

And here's yet another way that assumes that 

(1) the groups are separated by empty lines
(2) the first line always contains the file name
(3) "ERROR" may occur in any of the lines that follow

 def groups(lines):
return (
group
for key, group in itertools.groupby(lines, key=str.isspace)
if not key
)

with open("nohup.out") as f:
for group in groups(f):
first = next(group)
if any("ERROR" in line for line in group):
assert "XPT" in first
print(get_url(first))

 
>> --2018-07-14 21:26:45-- 
>> https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXIFF_F.XPT Resolving
>> wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39 Connecting to wwwn.cdc.gov
>> (wwwn.cdc.gov)|198.246.102.39|:443... connected. HTTP request sent,
>> awaiting response... 404 Not Found 2018-07-14 21:26:46 ERROR 404: Not
>> Found.
>> 
>> --2018-07-14 21:26:46-- 
>> https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXTOT_F.XPT Resolving
>> wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39 Connecting to wwwn.cdc.gov
>> (wwwn.cdc.gov)|198.246.102.39|:443... connected. HTTP request sent,
>> awaiting response... 404 Not Found 2018-07-14 21:26:46 ERROR 404: Not
>> Found.
>> 
>> --2018-07-14 21:26:46-- 
>> https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DRXFMT_F.XPT Resolving
>> wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39 Connecting to wwwn.cdc.gov
>> (wwwn.cdc.gov)|198.246.102.39|:443... connected. HTTP request sent,
>> awaiting response... 404 Not Found 2018-07-14 21:26:46 ERROR 404: Not
>> Found.
>> 
>> --2018-07-14 21:26:46-- 
>> https://wwwn.cdc.gov/Nchs/Nhanes/2009-2010/DSQ1_F.XPT Resolving
>> wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39 Connecting to wwwn.cdc.gov
>> (wwwn.cdc.gov)|198.246.102.39|:443... connected. HTTP request sent,
>> awaiting response... 404 Not Found 2018-07-14 21:26:47 ERROR 404: Not
>> Found.
>> 
>> --2018-07-14 21:26:47-- 
>> https://wwwn.cdc.gov/Nchs/Nhanes/1999-2000/DSII.XPT Resolving
>> wwwn.cdc.gov (wwwn.cdc.gov)... 198.246.102.39 Connecting to wwwn.cdc.gov
>> (wwwn.cdc.gov)|198.246.102.39|:443... connected. HTTP request sent,
>> awaiting response... 200 OK Length: 56060880 (53M)
>> [application/octet-stream] Saving to: ‘DSII.XPT’
>> 
> 


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


Re: Getting installed version

2018-07-21 Thread Peter J. Holzer
On 2018-07-20 08:04:33 +0200, Cecil Westerhof wrote:
> I can get the installed version of a package with:
> pip2 show cryptography | awk '/^Version: / { print $2 }'
> 
> But I was wondering if there is a better way.

Using pip probably is the most reliable way (for packages installed via
pip).

Most packages have version information embedded, and most of them use
the attribute __version__:

>>> import chardet
>>> chardet.__version__
'2.3.0'
>>> import colorama
>>> colorama.__version__
'0.3.2'
>>> import psycopg2
>>> psycopg2.__version__
'2.5.4 (dt dec pq3 ext)'
>>> import numpy
>>> numpy.__version__
'1.8.2'

But there are exceptions:

>>> import xlrd
>>> xlrd.__VERSION__
'0.9.2'

or even:

>>> import django
>>> django.get_version()
'1.7.11'

So you can't rely on that.

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | h...@hjp.at | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] Bit twiddling homework

2018-07-21 Thread Peter J. Holzer
On 2018-07-20 19:13:44 +1000, Chris Angelico wrote:
> On Fri, Jul 20, 2018 at 7:00 PM, Brian Oney via Python-list
>  wrote:
> > That's right I had forgotten about that. Thank you for the quick 
> > answer.Some fun:$ ipythonPython 2.7.13 (default, Nov 24 2017, 17:33:09) 
> > ...In [1]: j = 16; i = 1
> > In [2]: print(i+j); print(i|j)1717
> > In [3]: %timeit i+j1000 loops, best of 3: 65.8 ns per loop
> > In [4]: %timeit i|j1000 loops, best of 3: 73 ns per loop
> > In [5]: %timeit 16|11000 loops, best of 3: 28.8 ns per loop
> > In [6]: %timeit 16+11000 loops, best of 3: 28.8 ns per loop
> > I wonder why the difference between [3] and [4]. My mental ranking of speed 
> > of operations tells me it should be the other way around.
> > Are 16|1 and 16+1 internally the same operation (for integers)?
> 
> What you're seeing is nothing but noise. With numbers this low, you
> can't really judge anything.

Also, Brian is timing Python operations here, not CPU operations. In
order to execute an arithmetic or logical operation, the Python
interpreter has to execute dozens or hundreds of CPU operations. So the
single ADD or OR somewhere in the middle is swamped by other
instructions.

It is possible that the code performing a numeric addition is a bit
better optimized than the code performing a bitwise or. But looking at
the source code that doesn't seem to be the case.

Might be just an accident, although the difference is remarkably
reproducible.

Anybody have a CPU emulator handy to trace this clock by clock? ;-)

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | h...@hjp.at | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Edit with IDLE pull down menu

2018-07-21 Thread no
On Sat, 21 Jul 2018 08:52:45 -0700 (PDT), Rick Johnson
 wrote:

>n...@none.invalid wrote:
>> Terry Reedy wrote:
>
>[...]
>
>> You seem to be able to directly affect Python development.
>> If that is true, maybe you could remove the pull down
>> redundancy from one menu and add a pull down option to
>> another pull down menu.  If Python can modify the pull down
>> menus, it would be nice to be able to right click in a
>> folder (Windows) and have an option to create a new python
>> file with a .py extension like you can create a new text
>> document with a .txt extension.  OpenOffice adds this
>> option to create new OO files.
>
>Hmm, your idea is not terribly awful, but, you should
>consider that if a "Make New file.XXX" command was added to
>the file system context menu for _every_ possible file-type,
>*ZOINKS*, that'd be a frighteningly long list of commands to
>scroll through! And then, after creating the empty file in
>this manner, you'd still have to open the file for editing.
>Thus, a two step process.
>
>A better solution is to use an IDE. Sure, you may have to
>navigate to the appropriate directory, but once you're
>there, any new documents created from the interface (aka:
>"File->New") will default to the current working directory.

I don't remember if OO ever asked for permission, but Winrar did.

I would hope that install programs asked for permission before adding
something like this.  And take it with them when they leave.


The reason I find this useful is because most of my practice programs
so far "import random".  I have a shell file that I keep and I copy it
to a blank file to start another practice problem.  If I try to just
"save as" something else, I forget sometimes.


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


Re: pattern block expression matching

2018-07-21 Thread Dan Sommers
On Sat, 21 Jul 2018 17:37:00 +0100, MRAB wrote:

> On 2018-07-21 15:20, aldi.kr...@gmail.com wrote:
>> Hi,
>> I have a long text, which tells me which files from a database were 
>> downloaded and which ones failed. The pattern is as follows (at the end of 
>> this post). Wrote a tiny program, but still is raw. I want to find term 
>> "ERROR" and go 5 lines above and get the name with suffix XPT, in this first 
>> case DRXIFF_F.XPT, but it changes in other cases to some other name with 
>> suffix XPT. Thanks, Aldi
>> 
>> # reading errors from a file txt
>> import re
>> with open('nohup.out', 'r') as fh:
>>lines = fh.readlines()
>>for line in lines:
>>m1 = re.search("XPT", line)
>>m2 = re.search('ERROR', line)
>>if m1:
>>  print(line)
>>if m2:
>>  print(line)
>> 
> Firstly, you don't need regex for something has simple has checking for 
> the presence of a string.
> 
> Secondly, I think it's 4 lines above, not 5.
> 
> 'enumerate' comes in useful here:
> 
> with open('nohup.out', 'r') as fh:
>  lines = fh.readlines()
>  for i, line in enumerate(lines):
>  if 'ERROR' in line:
>  print(line)
>  print(lines[i - 4])

Where's awk when you need it?

import fileinput
for line in fileinput.fileinput('nohump.out'):
if 'XPT' in line:
line_containing_filename = line
if 'ERROR' in line:
print(line_containing_filename)

I think Aldi's original approach is pretty good.

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


functions vs methods

2018-07-21 Thread Sharan Basappa
Is there a difference between functions and methods in Python.

For example, this is the text from tutorialpoint on Python:
Python includes the following list functions - cmp, len etc.

Python includes following list methods - append, count

A related question.

Refer to the following lines:
1) len(list) 
2) list.append()

The first line passes list to a len function while the second line calls append 
method in list.

So, how to interpret this?

In the first case, len is a function that python provides to which list can be 
passed and in the second case, append is a method within list class?

If my interpretation is correct, why not make len also as a part of list class 
itself?

Thanks in advance

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


Re: functions vs methods

2018-07-21 Thread Lele Gaifax
Sharan Basappa  writes:

> Refer to the following lines:
> 1) len(list) 
> 2) list.append()
>
> In the first case, len is a function that python provides to which list can 
> be passed and in the second case, append is a method within list class?
>
> If my interpretation is correct, why not make len also as a part of list 
> class itself?

Yes, that's correct. For the reason, see
https://docs.python.org/3/faq/design.html#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list

ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
l...@metapensiero.it  | -- Fortunato Depero, 1929.

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


Re: Cookies not showing up in environ

2018-07-21 Thread abc abc
> I think one of the main issues is that you don't seem to have decided
> whether you're writing a WSGI application or a Django application.

Yes, I suppose I thought Django had to use wsgi to process requests, I didn't 
know there were 'two' options here. Does your example represent one or the 
other?

My mistake, I should have mentioned I was using Django 1.11 so I had to use url 
instead of path in urls.py. Below, I have tried to provide as much information 
as possible.

I tried with just the files you provided with slight modifications:

project_folder/app/views.py:

from django.http import HttpResponse

def cookies(request):
return HttpResponse(repr(request.COOKIES),
'text/plain; charset=utf-8')

def index(request):
print 'INDEX: '
print request.COOKIE
return HttpResponse('this is the response')


project_folder/app/urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
url('cookies', views.cookies),
url('index', views.index),
]


project_folder/app/wsgi.py

def application(environ, start_response):
start_response('200 OK',
   [('Content-Type', 'text/plain; charset=utf-8')])
return [environ.get('HTTP_COOKIE', '').encode('utf-8')]


>From the project folder, I ran 'python manage.py runserver'

Cleared all cookies in the browser, and went to localhost:8000/cookies which 
loaded with no error in the console or browser. No cookies were created in the 
browser preferences.

I tried refreshing the browser for localhost:8000/index but still no cookies. 
Also, for views.py, the print statement 'INDEX: ' did not appear in the 
console, nor did the http response string I returned (in either browser or 
console). So something is not getting processed right. In my previous attempts 
(to your example code) I had no issue rendering templates and html. The only 
thing that didn't seem to work were the cookies.


Console Output:

Performing system checks...

System check identified no issues (0 silenced).
July 21, 2018 - 20:47:24
Django version 1.11.13, using settings 'omicron.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[21/Jul/2018 20:47:34] "GET / HTTP/1.1" 200 0
[21/Jul/2018 20:47:34] "GET /favicon.ico HTTP/1.1" 200 0
[21/Jul/2018 20:47:54] "GET / HTTP/1.1" 200 0
[21/Jul/2018 20:47:58] "GET /cookies HTTP/1.1" 200 0
[21/Jul/2018 20:47:58] "GET /favicon.ico HTTP/1.1" 200 0
[21/Jul/2018 20:48:07] "GET /index HTTP/1.1" 200 0
[21/Jul/2018 20:48:08] "GET /favicon.ico HTTP/1.1" 200 0
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Cookies not showing up in environ

2018-07-21 Thread abc abc
> I think one of the main issues is that you don't seem to have decided
> whether you're writing a WSGI application or a Django application.

Yes, I suppose I thought Django had to use wsgi to process requests, I didn't 
know there were 'two' options here. Does your example represent one or the 
other?

My mistake, I should have mentioned I was using Django 1.11 so I had to use url 
instead of path in urls.py. Below, I have tried to provide as much information 
as possible.

I tried with just the files you provided with slight modifications:

project_folder/app/views.py:

from django.http import HttpResponse

def cookies(request):
return HttpResponse(repr(request.COOKIES),
'text/plain; charset=utf-8')

def index(request):
print 'INDEX: '
print request.COOKIE
return HttpResponse('this is the response')


project_folder/app/urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
url('cookies', views.cookies),
url('index', views.index),
]


project_folder/app/wsgi.py

def application(environ, start_response):
start_response('200 OK',
   [('Content-Type', 'text/plain; charset=utf-8')])
return [environ.get('HTTP_COOKIE', '').encode('utf-8')]


>From the project folder, I ran 'python manage.py runserver'

Cleared all cookies in the browser, and went to localhost:8000/cookies which 
loaded with no error in the console or browser. No cookies were created in the 
browser preferences.

I tried refreshing the browser for localhost:8000/index but still no cookies. 
Also, for views.py, the print statement 'INDEX: ' did not appear in the 
console, nor did the http response string I returned (in either browser or 
console). So something is not getting processed right. In my previous attempts 
(to your example code) I had no issue rendering templates and html. The only 
thing that didn't seem to work were the cookies.


Console Output:

Performing system checks...

System check identified no issues (0 silenced).
July 21, 2018 - 20:47:24
Django version 1.11.13, using settings 'app.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[21/Jul/2018 20:47:34] "GET / HTTP/1.1" 200 0
[21/Jul/2018 20:47:34] "GET /favicon.ico HTTP/1.1" 200 0
[21/Jul/2018 20:47:54] "GET / HTTP/1.1" 200 0
[21/Jul/2018 20:47:58] "GET /cookies HTTP/1.1" 200 0
[21/Jul/2018 20:47:58] "GET /favicon.ico HTTP/1.1" 200 0
[21/Jul/2018 20:48:07] "GET /index HTTP/1.1" 200 0
[21/Jul/2018 20:48:08] "GET /favicon.ico HTTP/1.1" 200 0
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Edit with IDLE pull down menu

2018-07-21 Thread no
On Sat, 21 Jul 2018 14:34:15 -0700 (PDT), Rick Johnson
 wrote:

This is really the code I keep copying.

import random
from random import randint
a = [5, 10, 15, 20, 25, 30, 35, 40]
b = ["Rock","Paper","Scissors","Lizard ","Spock"]


I am lazy and don't type well, so I leave out some details when
posting.

I don't know why the program I needed randint for didn't work with
just import random, but I moved on without lingering on it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Cookies not showing up in environ

2018-07-21 Thread Jon Ribbens
On 2018-07-21, abc abc  wrote:
>> I think one of the main issues is that you don't seem to have decided
>> whether you're writing a WSGI application or a Django application.
>
> Yes, I suppose I thought Django had to use wsgi to process requests,
> I didn't know there were 'two' options here.

Django does use wsgi to process requests. But if you've written
an application in Django, you don't need to then write it again
without Django - Django has its own wsgi app that will call the
Django app for you.

> Does your example represent one or the other?

Both - I gave two alternatives, and labelled each. You only need one.

> project_folder/app/wsgi.py
>
> def application(environ, start_response):
> start_response('200 OK',
>[('Content-Type', 'text/plain; charset=utf-8')])
> return [environ.get('HTTP_COOKIE', '').encode('utf-8')]

You should delete that and change it back to whatever 'django
startproject' gave you originally for wsgi.py. If you're writing
a django app then you don't need to also write a wsgi app.

> Cleared all cookies in the browser, and went to
> localhost:8000/cookies which loaded with no error in the console or
> browser. No cookies were created in the browser preferences.

Well, you're not setting any cookies. You'd need to do something like:

 def cookies(request):
 response = HttpResponse(repr(request.COOKIES),
 'text/plain; charset=utf-8')
 response.set_cookie('mycookie', 'value')
 return response

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


Re: Edit with IDLE pull down menu

2018-07-21 Thread MRAB

On 2018-07-22 00:44, no@none.invalid wrote:

On Sat, 21 Jul 2018 14:34:15 -0700 (PDT), Rick Johnson
 wrote:

This is really the code I keep copying.

import random
from random import randint
a = [5, 10, 15, 20, 25, 30, 35, 40]
b = ["Rock","Paper","Scissors","Lizard ","Spock"]


I am lazy and don't type well, so I leave out some details when
posting.

I don't know why the program I needed randint for didn't work with
just import random, but I moved on without lingering on it.

When you import 'random', that name refers to the module itself. You can 
refer to 'randint', which is defined in that module, by writing 
"random.randint".


Alternatively, as you've done, you can import 'randint' directly from 
the 'random' module.

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


import in code

2018-07-21 Thread Abdur-Rahmaan Janhangeer
i have found some reputable books that include import within code

with ...
import x

if ...
import y

def ...
 import z

according to me they should be placed at the top. but an advantage of it is
optimisation where you only load modules if necessary

so, import within code can be called unpythonic?

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Make, Sphinx and Windows

2018-07-21 Thread Abdur-Rahmaan Janhangeer
normally when you use make with sphinx, it should build and tell you errors
(so that reviewers don't have to correct it manually) i have been doing
some contribs to french docs translation but my make is a bit crazy :

https://www.pythonmembers.club/wp-content/uploads/2018/07/make-win.png

any idea?

thanks
---
Abdur-Rahmaan Janhangeer
https://github.com/abdur-rahmaanj
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: functions vs methods

2018-07-21 Thread Sharan Basappa
Thanks a lot.

On Sunday, 22 July 2018 04:02:23 UTC+5:30, Rick Johnson  wrote:
> On Saturday, July 21, 2018 at 2:06:21 PM UTC-5, Sharan Basappa wrote:
> > Is there a difference between functions and methods in Python.
> 
> Generally speaking, functions and methods are basically two
> words describing the exact same thing: "small packages of
> reusable code". 
> 
> An easy way to think about it for the
> uninitiated is that, functions came first, and methods are a
> special kind of function which is owned by what we
> programmers call "Objects". 
> 
> You can learn more about methods
> and objects (and a wholelotta other stuff too) by reading
> up on "Object Oriented Programming" (aka: OOP). There are
> tons of tutorials and examples on the web. Ask Google. 
> 
> "What???" o_O
> 
> "Can you repeat that?..."
> 
> [listening carefully]
> 
> "Her???"
> 
> "No, not _her_!"
> 
> "To your left a bit..."
> 
> "..."
> 
> "No, not _that_ left..." (/ロ°)/
> 
> "Your _other_ left!" \(°ロ\)
> 
> "..."
> 
> "Oh... for guido's sake, man..." (-‸ლ)
> 
> "THE ONE WITH THE _PURPLE_ HAIR!!!" (屮゚Д゚)屮
> 
> "..."
> 
> "BINGO!!!" :-)
> 
> "Now, ask her..." 
> 
> 
> > [...]
> > 
> > A related question.
> > 
> > Refer to the following lines:
> > 1) len(list) 
> > 2) list.append()
> > 
> > The first line passes list to a len function while the
> > second line calls append method in list.  So, how to
> > interpret this?  In the first case, len is a function that
> > python provides to which list can be passed and in the
> > second case, append is a method within list class?
> 
> 
> First, get yer terminology correct...
> 
> list _object_. 
> 
> Not _class_. 
> 
> _Object_!!!
> 
> "Class" refers to the syntactical representation of an OOP
> _object_ -- aka: meaning that "class" is all the code
> written to _define_ an object -- while _object_, refers to
> the "live thing" that actually does stuff. For instance: in
> the case of a python list _object_ (1) the _object_ acts as
> a container for other "live objects", and (2) the _object_
> exposes an interface so we can call methods that perform
> certain predefined tasks.
> 
> > If my interpretation is correct, why not make len also as a
> > part of list class itself?
> 
> Simple Answer: because Python is not a _pure_ OOP language. 
> 
> Yes, python allows us to write code in the OOP paradigm (and
> many others), but unlike languages such as, say, Ruby and
> Java (which are pure OOP languages), python decided to go
> down a different route. And there are good reasons to _not_
> be a pure OOP language, and of course, there are certain
> "unintuitive seeming effects" because of that design choice.
> And you've stumbled upon one here. 
> 
> Congrats!
> 
> Once you familiarize yourself with Python's multi-paradigm
> design, and you study more about OOP and experience the
> onerous of purely OOP languages, you will understand why
> python's designers decided to go this route.
> 
> Until then, i'd worry about something more important. Like
> actually mastering the language. And once you've mastered
> the language, then you earn the right to sit around here all
> day and complain about everything. Like any good Pythinistas
> would do.

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


print & string formatting

2018-07-21 Thread Sharan Basappa
Folks,

I get a lot confused while using print functions in Python.

For example, I get the same results for the following code:

str = "one two three"

print str
print "%s" %(str)

So, what is the need to use the second method which I see being used in many 
programs I am referring to

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


Re: import in code

2018-07-21 Thread Cameron Simpson

On 22Jul2018 06:43, Abdur-Rahmaan Janhangeer  wrote:

i have found some reputable books that include import within code

with ...
   import x

if ...
   import y

def ...
import z

according to me they should be placed at the top. but an advantage of it is
optimisation where you only load modules if necessary

so, import within code can be called unpythonic?


It is discouraged, because when the imports are at the top they're really 
obvious. That is a huge gain for maintenance and readability.


Importing a module is _usually_ pretty cheap. There are some reasons to put off 
imports until the code which needs them runs, but they are all fairly rare:


Circular imports: 2 codependent modules. If you have:

 module A:
   import B

 module B:
   import B

That won't work: the second import (whichever it turns out to be) will fail.  
One workaround is to make one of the modules put off the import. A better 
approach is usually to redesign things so that they don't do a mutual import 
(move classses etc around, or merge them). This is always feasible, but often 
is.


External dependencies: if your module only sometimes needs a third party 
facility, you might put off importing that 3rd party module until it is 
actually needed.


As an example, I have a personal project, not yet released, which has a "mount" 
command, presenting stuff as a local filesystem using the "llfuse" Python 
module. Aside from that, everything else is self contained. By making the 
"mount" command do the "import llfuse", there isn't a general requirement for 
people to install llfuse unless the particularly want that facility.


Another example is probing the local environment for available facilities. You 
may have code that probes for various database backends, for example, and hooks 
up those found. This is a runtime thing which can happen in the main import 
block, but may well live better in some "probing" function lower in the module.


Antoher example is a variant on the above: modules like SQLAlchemy will accept 
"database connection URIs", like "mysql://hostname/...". The supporting module 
might only be loaded if such a URI is encountered.


Serverless or tiny workload situations: when a Python program is invoked very 
frequently, particularly to perform a tiny task, the fewer imports there are 
the (slightly) faster it will run. Also, sometimes a module might be expensive 
to import, itself pulling in a lot of other things. In a serverless 
architecture, Python gets invoked on every call, so making the setup (imports 
etc) as cheap as possible is suddenly much more important.


All of these situations may benefit from doing conditional or deferred imports.  
But try to avoid them until you have a specific need.


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


Re: import in code

2018-07-21 Thread Cameron Simpson

On 22Jul2018 14:45, Cameron Simpson  wrote:

Circular imports: 2 codependent modules. If you have:

module A:
  import B

module B:
  import B

That won't work: the second import (whichever it turns out to be) will 
fail.  One workaround is to make one of the modules put off the 
import. A better approach is usually to redesign things so that they 
don't do a mutual import (move classses etc around, or merge them). 
This is always feasible, but often is.


That should be "This _isn't_ always feasible, but often is".

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


Re: print & string formatting

2018-07-21 Thread Abdur-Rahmaan Janhangeer
*Folks,I get a lot confused while using print functions in Python.For
example, I get the same results for the following code:str = "one two
three"print strprint "%s" %(str)So, what is the need to use the second
method which I see being used in many programs I am referring to*

well
1) that is more convenient than concatenation ""+x+""
2) no need for casting
x = 64
"%d" %(x)
3) the .format() or f'' makes it simpler and reflects the real spirit of py
"{}".format(y) # no need to specify s or d etc


-- 
Abdur-Rahmaan Janhangeer
https://github.com/abdur-rahmaanj
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: functions vs methods

2018-07-21 Thread dieter
Sharan Basappa  writes:

> Is there a difference between functions and methods in Python.

Somewhat simplified: a method is a function with the
method's associated object implicitly passed as first argument.

For a Python defined method "m", you can get the corresponding
function via "m.__func__" (this is not necessarily true
for methods defined in "C", among them built-in methods).

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


Re: print & string formatting

2018-07-21 Thread Chris Angelico
On Sun, Jul 22, 2018 at 2:53 PM, Abdur-Rahmaan Janhangeer
 wrote:
> *Folks,I get a lot confused while using print functions in Python.For
> example, I get the same results for the following code:str = "one two
> three"print strprint "%s" %(str)So, what is the need to use the second
> method which I see being used in many programs I am referring to*
>
> well
> 1) that is more convenient than concatenation ""+x+""
> 2) no need for casting
> x = 64
> "%d" %(x)
> 3) the .format() or f'' makes it simpler and reflects the real spirit of py
> "{}".format(y) # no need to specify s or d etc

Not sure what you mean by "the real spirit of Python", but you can use
%s with literally any object at all, and it'll work - in fact, it'll
do the same thing that {} does in a format string.

But yes, the point of the formatting operations is to do more than
just format a string.

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


Re: import in code

2018-07-21 Thread Abdur-Rahmaan Janhangeer
On Sun, Jul 22, 2018 at 8:49 AM Cameron Simpson  wrote:

> On 22Jul2018 14:45, Cameron Simpson  wrote:
> >Circular imports: 2 codependent modules.


apart from circular imports?
-- 
Abdur-Rahmaan Janhangeer
https://github.com/abdur-rahmaanj
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: import in code

2018-07-21 Thread Abdur-Rahmaan Janhangeer
>
>
> apart from circular imports?
>

sorry your last mail was sent to spam by gmail. now seeing it . thank you !

-- 
Abdur-Rahmaan Janhangeer
https://github.com/abdur-rahmaanj
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print & string formatting

2018-07-21 Thread Cameron Simpson

On 21Jul2018 21:33, Sharan Basappa  wrote:

I get a lot confused while using print functions in Python.

For example, I get the same results for the following code:

str = "one two three"


Pleasetry not to name variables after builtin classes ("str" is the name of 
Python's string class).



print str
print "%s" %(str)

So, what is the need to use the second method which I see being used in many 
programs I am referring to


For a bare "%s", one would normally just write str(s) where "s" is your string 
variable.


The % formatting is usually for (a) more complex messages or (b) separating the 
message format from the values. Example:


 print("The time is %s and the place is %s." % (when, where))

Instead of the much harder to read and maintain:

 print("The time is", str(when), "and the place is", str(where), ".")

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


Re: import in code

2018-07-21 Thread dieter
Abdur-Rahmaan Janhangeer  writes:

> i have found some reputable books that include import within code
>
> with ...
> import x
>
> if ...
> import y
>
> def ...
>  import z
>
> according to me they should be placed at the top. but an advantage of it is
> optimisation where you only load modules if necessary

Such "local" imports are sometimes important to avoid
circular imports.

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