Re: semicolon at end of python's statements

2013-09-03 Thread Antoon Pardon

Op 03-09-13 01:17, Modulok schreef:
> 
> So? Indeed there are too many people looking at these things as fighting
> for the one true way. That is IMO part a big part of the problem. I have
> no problem if someone else uses a different style than I do. Python as
> a language tries too hard to enforce a one true way.
>  
> Try maintaining a non-trivial body of JavaScript, or Perl (that you didn't
> write) for a while. You'll soon appreciate the One True Way of thinking lol.

My impression is that everyone appreciates the One True Way but only
because they identify their own way as the One True Way. And sure it
can be a good thing to enforce a One True Way for a specific project
or for all company code, but there is no need that all projects would
need the same One True Way.

-- 
Antoon Pardon
-- 
http://mail.python.org/mailman/listinfo/python-list


Cannot form correctly the FORM part of the header when sending mail

2013-09-03 Thread Ferrous Cranus

Hello,
i have written the following snipper of code to help me send mail:


=
# if html form is submitted then send user mail
#
if( mailform ):

try:
if (FROM is None) or (MESSAGE is None) or ('@' not in FROM) or 
('Γράψε μου εδώ' in MESSAGE):
print( "Συμπλήρωσε σωστά το mail σου 
και δώσε το σχολιασμό σου!" )

else:
# prepare mail data
TO = "[email protected]"

SUBJECT = u"Mail από τον επισκέπτη: ( %s )" % FROM

MESSAGE = "From: %s\r\n" + "To: %s\r\n" + "Subject: %s\r\n" 
+ MESSAGE + "\r\n"

MESSAGE = MESSAGE % ( FROM, TO, SUBJECT )
MESSAGE = MESSAGE.encode('utf-8')

# open Gmail's SMTP server
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()

# next, log in to the server
server.login("[email protected]", "rmrcdherpbsfggcw")

# send the mail
server.sendmail( FROM, [TO], MESSAGE )

print( "Ευχαριστώ πολύ για το 
ενδιαφέρον! Θα επικοινωνήσω μαζί σου άμεσα :-)" )

except Exception as e:
print( repr(e), file=open( '/tmp/err.out', 'a' ) )

sys.exit(0)
===


It works as expected, but the the problem is that it display the FROM 
part as being send from ,my personal GMail account when it supposed to 
be shown the format variable field that was passed by index.html to the 
mail.py script.


Si there a workaround for that please?
--
Webhost 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot form correctly the FORM part of the header when sending mail

2013-09-03 Thread feedthetroll
Am Dienstag, 3. September 2013 09:48:13 UTC+2 schrieb Ferrous Cranus:
> Hello,
> i have written the following snipper of code to help me send mail:
> ...
>  server.login("[email protected]", "..")
HE DID IT AGAIN! The login works with the posted password!
Nikos, you should change your password IMMEDIATELY!

> ... 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to execute command on remote windows machine

2013-09-03 Thread Jean-Michel Pichavant


- Original Message -
> Hi alex
> 
> I tried the command you suggested however it is giving me following
> error.
> 
> ERROR: The RPC server is unavailable.

Hi,

Please do not top post :)
If python is installed on the remote machine, using execnet 
http://codespeak.net/execnet/ is very easy. Its only requirement is python 
being installed on both machines.

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to split with "\" character, and licence copyleft mirror of ©

2013-09-03 Thread Tim Chase
On 2013-09-03 02:06, Steven D'Aprano wrote:
>> So the real bug is with the parser.
> 
> It is likely that nobody noticed this bug in the first place
> because the current behaviour doesn't matter for regexes, which is
> the primary purpose of raw strings. You can't end a regex with an
> unescaped backslash, so r'abc\'' is an illegal regex and it doesn't
> matter if you can't create it.

I'd contend that the two primary purposes of raw strings (this is
starting to sound like a Spanish Inquisition sketch) are regexes and
DOS/Win32 file path literals.  And I hit this trailing-backslash case
all the time, as Vim's path-completion defaults to putting the
trailing backslash at the end.  So I might be entering a literal like

  r"c:\win

and hit  which expands to

  r"c:\Windows\

for which I then need to both remove the backslash and close the
quote.  If Python's parser just blithely ignored terminal
backslashes, I could just close the quote and get on with my day.

-tkc



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


Re: Cannot form correctly the FORM part of the header when sending mail

2013-09-03 Thread Ferrous Cranus

Στις 3/9/2013 12:33 μμ, ο/η [email protected] έγραψε:

Am Dienstag, 3. September 2013 09:48:13 UTC+2 schrieb Ferrous Cranus:

Hello,
i have written the following snipper of code to help me send mail:
...
  server.login("[email protected]", "..")

HE DID IT AGAIN! The login works with the posted password!
Nikos, you should change your password IMMEDIATELY!

..
OMG!

I cannot believe i'm being *that* careless, so many times.


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


Re: sqlite issue in 2.7.5

2013-09-03 Thread Alister
On Mon, 02 Sep 2013 22:13:27 +, Joseph L. Casale wrote:

> I have been battling an issue hopefully someone here has insight with.
> 
> I have a database with a few tables I perform a query against with some
> joins against columns collated with NOCASE that leverage = comparisons.
> 
> Running the query on the database opened in sqlitestudio returns the
> results in under a minute. Running the query in Python with sqlite3
> doesn't return results for several hours. I haven't figured out what
> pragmas or other shortcuts sqlitestudio uses to provide the results so
> fast.
> 
> Using apsw returns the dataset nearly instantaneously but the
> connection/cursor/commit differences are too drastic and would force far
> too large a rewrite for the module change.
> 
> Anyone by chance know the underlying changes required in the sqlite3
> module to replicate what sqlitestudio is doing behind the scenes?
> 
> Thanks,
> jlc

you are almost certainly doing something drastically wrong
can you provides examples of your code & the data structure otherwise I 
doubt that anyone will be able to assist.




-- 
To err is human, to forgive, beyond the scope of the Operating System.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to execute command on remote windows machine

2013-09-03 Thread random832
On Tue, Sep 3, 2013, at 0:45, [email protected] wrote:
> Hi Guys, 
> 
> I have a requirement where i need to kill one process on remote windows
> machine. 
> Following command just works fine if i have to kill process on local
> machine 
> 
> os.system('taskkill /f /im processName.exe')
> 
> However I am not able to figure out how to execute this command on remote
> windows machine. 
> 
> Note: my local machine is also windows (machine from where i have to
> execute command)
> 
> so is there any way i can execute command from windows machine on remote
> windows machine ?

The taskkill command actually has an option for this: /S. I don't know
what mechanism it uses or what you would have to do to give yourself
permission to use it.


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


Unable to redirect the subprocess CMD.exe to txt file. Please help !!!

2013-09-03 Thread Venkatesh
Hello comp.lang.python Group,

I am trying to invoke a subprocess in Python as below 

import sys
import time
import os
import subprocess
DETACHED_PROCESS = 0x0008

path = r'C:\Windows\System32\cmd.exe /k ping www.google.com -n 4 >> temp.txt'
p = subprocess.Popen("%s"%(path), stdout = subprocess.PIPE, stderr = 
subprocess.STDOUT, creationflags=DETACHED_PROCESS)

With this code, unable to invoke the subprocess and hence not able to store the 
Ping statistics in the file.

Any help on this OR any better way of achieving this??


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


Re: How to execute command on remote windows machine

2013-09-03 Thread Jean-Michel Pichavant

- Original Message - 

> I tried it, however it seems really complicated.

> If you have used it before, can you show me how can i do it ?

> Gaurang Shah
> Blog: qtp-help.blogspot.com
> Mobile: +91 738756556

Please don't ask question off-list.

It's not complicated at all.

The documentation has a lot of examples:
http://codespeak.net/execnet/example/test_info.html#execute-source-code-in-subprocess-communicate-through-a-channel

makegateway by defaut execute the code on the local machine. You simply need to 
use something like 
makegateway("ssh=myRemoteMachine")

cheers,

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to execute command on remote windows machine

2013-09-03 Thread 88888 Dihedral
[email protected]於 2013年9月3日星期二UTC+8下午12時45分57秒寫道:
> Hi Guys, 
> 
> 
> 
> I have a requirement where i need to kill one process on remote windows 
> machine. 
> 
> Following command just works fine if i have to kill process on local machine 
> 
> 
> 
> os.system('taskkill /f /im processName.exe')
> 
> 
> 
> However I am not able to figure out how to execute this command on remote 
> windows machine. 
> 
> 
> 
> Note: my local machine is also windows (machine from where i have to execute 
> command)
> 
> 
> 
> so is there any way i can execute command from windows machine on remote 
> windows machine ?

This is trivial. First install the VNC on the remote site and 
make sure your VNC is working in the proper forground.

Just write a mouse/keyboard emulator service on the remote site 
with the propper port opened by python scripts.

Use the control computer  to send commands  to the remote site.

This scheme will work under unix-linux-windows OS.

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


Re: UnicodeDecodeError issue

2013-09-03 Thread Steven D'Aprano
On Tue, 03 Sep 2013 08:45:00 +1000, Chris Angelico wrote:

> On Tue, Sep 3, 2013 at 12:44 AM, MRAB 
> wrote:
>> I don't know Greek either, and I don't think there's any other language
>> that uses the Greek alphabet.
> 
> Assuming you don't count mathematics as a language.


There are a few languages which use the Greek alphabet, with variations. 
Coptic is the main one, although Greek and Coptic letters have their own 
Unicode symbols, in order to support works which need to distinguish them.

Armenian and, of course, Cyrillic, are derived from the Greek alphabet; 
actually so is the Latin alphabet.

Other languages that used, or use, the Greek alphabet include quite a few 
ancient languages, including Gaulish and Bactrian. Old Nubian in the 
Middle Ages used the Greek alphabet plus a few additional letters. A 
number of Slavic languages used the Greek alphabet, although now they use 
Cyrillic. Some Albanian dialects still use the Greek alphabet, as do a 
couple of Turkic languages from the Balkans. See the Wikipedia entry on 
the Greek alphabet for more.


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


Re: Unable to redirect the subprocess CMD.exe to txt file. Please help !!!

2013-09-03 Thread William Ray Wing
On Sep 3, 2013, at 9:54 AM, Venkatesh  wrote:

> Hello comp.lang.python Group,
> 
> I am trying to invoke a subprocess in Python as below 
> 
> import sys
> import time
> import os
> import subprocess
> DETACHED_PROCESS = 0x0008
> 
> path = r'C:\Windows\System32\cmd.exe /k ping www.google.com -n 4 >> temp.txt'
> p = subprocess.Popen("%s"%(path), stdout = subprocess.PIPE, stderr = 
> subprocess.STDOUT, creationflags=DETACHED_PROCESS)
> 
> With this code, unable to invoke the subprocess and hence not able to store 
> the Ping statistics in the file.
> 
> Any help on this OR any better way of achieving this??
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list


I use the following in OS-X, should be very similar in Windows.

   import subprocess
   ping_result = subprocess.Popen(['ping', '-c1', '-t1', self.target_IP], 
stderr=subprocess.PIPE, stdout = subprocess.PIPE).communicate()[0]

self.target_IP is a string containing the IP address, which is defined 
elsewhere.
ping_result contains the complete returned string from the ping command.  Note 
the -c switch (count = 1 ping packet) and the -t switch (force exit after one 
second).
you will have to parse the returned string to extract the stats.

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


Re: UnicodeDecodeError issue

2013-09-03 Thread wxjmfauth
Le lundi 2 septembre 2013 16:44:34 UTC+2, MRAB a écrit :
> On 02/09/2013 13:24, Dave Angel wrote:
> 
> > On 2/9/2013 07:56, MRAB wrote:
> 
> >
> 
> >> On 02/09/2013 12:38, Dave Angel wrote:
> 
> >
> 
> > 
> 
> >
> 
> >>> ¶γνωστοόνομα συστήματος
> 
> >>>
> 
> >>> I don't have a clue what it might be;  it's not English, and I don't
> 
> >>> know whatever language it may be in.
> 
> >>>
> 
> >> You don't recognise Greek?
> 
> >
> 
> > I recognize most of those as Greek characters, but as I said, I don't
> 
> > know Greek.  And because I can't recognize words, I can't assume it
> 
> > might not be some other language that uses the same glyphs.
> 
> >
> 
> I don't know Greek either, and I don't think there's any other language
> 
> that uses the Greek alphabet.
> 
> 
> 
> >>
> 
> >>> Does that string make any sense to you?  You may want to try it on your
> 
> >>> own machine, since the email may obscure the encoding.  Or you might
> 
> >>> want to do the decode using whatever the default encoding is for that
> 
> >>> server.
> 
> >>>
> 
> >>> The Linux 'file' utility thinks this string is in ISO-8859, so you might
> 
> >>> want to try a decode('ISO-8859-1') as well.  (and maybe  ISO-8859-2, -3,
> 
> >>> -4, and -5)
> 
> >>>
> 
> >> It's ISO-8859-7 (Greek).
> 
> >



The Latin alphabet uses Greek lettering.

The Cyrillic alphabet uses Greek lettering.

Greek: One should not confuse modern Greek
with ancient Greek, polytonic Greek full
of diacritics.

Plenty of European languages (~15) based on the Latin
alphabet uses some ancient Greek diacritics.

Now unicode.

Everything is working very smoothly with the endorsed coding
schemes of Unicode.org.

Expectedly it fails (behaves badly) with Python and its 
Flexible Sting Representation, mainly because it relies on
the latin-1 (iso-8859-1) set.

To take the problem the other way, one can take these
linguistic ascpects to illustrate the wrong design of
the FSR.

jmf

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


Re: Unable to redirect the subprocess CMD.exe to txt file. Please help !!!

2013-09-03 Thread random832


On Tue, Sep 3, 2013, at 9:54, Venkatesh wrote:
> Hello comp.lang.python Group,
> 
> I am trying to invoke a subprocess in Python as below 
> 
> import sys
> import time
> import os
> import subprocess
> DETACHED_PROCESS = 0x0008
> 
> path = r'C:\Windows\System32\cmd.exe /k ping www.google.com -n 4 >>
> temp.txt'
> p = subprocess.Popen("%s"%(path), stdout = subprocess.PIPE, stderr =
> subprocess.STDOUT, creationflags=DETACHED_PROCESS)
> 
> With this code, unable to invoke the subprocess and hence not able to
> store the Ping statistics in the file.
> 
> Any help on this OR any better way of achieving this??

You should use /c, instead of /k. /k creates an interactive prompt.

I think you're being a bit overly complicated though by invoking cmd at
all. What about this?

subprocess.Popen("ping www.google.com -n 4",
stdout=open('temp.txt','a'), ...)
-- 
https://mail.python.org/mailman/listinfo/python-list


to be pythonic: should caller or callee log?

2013-09-03 Thread Gildor Oronar
What would you choose? Do you put logging routine into caller or callee? 
My intuitive answer is "callee does the logging, because that's where 
action takes place", like this:


class Account():
def transaction(self, amount, target):
logging.info("Start transaction of %s to %s" % (amount, target))
...

if '__name__' == '__main__'

account.transaction(amount, target)


Simple and easy. Put logging code to the caller would be tedious - the 
function is called about 20 times in different places.


So far so good, but we grew up to have 10 different account classes:

class AbsctractAccount():

class CreditAccount(AbstractAccount):
def transaction(self, amount, target):
logging.info("Start transaction of %s to %s" % (amount, target))
...

class DebitAccount(AbstractAccount):
def transaction(self, amount, target):
logging.info("Start transaction of %s to %s" % (amount, target))
...

class SomeOtherAccount(...)


Then letting the callee do the logging is also tedious now.

What is the best practise here?

If, for the convenience, we define transaction function in 
AbstractAccount to just do the logging, and change inherited classes, 
like this:


class AbsctractAccount():
def transaction(self, amount, target):
logging.info("Start transaction of %s to %s" % (amount, target))

class DebitAccount(AbstractAccount):
def transaction(self, amount, target):
super().transaction(amount,target)


Then we gethered logging code pieces all to one place, but it begets two 
other problems.


1. It is a "surprise" that super().transaction must be called first, not 
last, and that it does only the logging.


2. The code used to check whether "transaction" is implemented:

if hasAttr(DebitAccount, 'transaction'): # clear to read

has to be changed to check whether "transaction" is inherited:

if not DebitAccount.transaction is AbstractAccount.transaction:

whose purpose is confusing, and whose cause is a little surprise too. 
Also, the pythonic "boldly calling and watching for exception" stopped 
working, because instead of getting AttributeError, we would get a line 
of log and nothing more.


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


Re: Editing tabular data

2013-09-03 Thread rusi
On Friday, August 2, 2013 12:05:53 PM UTC+5:30, Ben Finney wrote:
> Skip Montanaro writes:
> 
> > I really love Emacs, however... […]
> >
> > This is clearly a case where choosing the proper tool is important. I
> > agree that using a spreadsheet to edit a 3x5 CSV file is likely
> > overkill (might just as well use Notepad or TextEdit), but tabular
> > data are tabular data, no matter how they might be delimited, and if
> > there are many of those little data critters, there are better tools
> > than a text editor (or Python IDE) for maintaining them.
> 
> It seems an obvious thing for powerful text editors like Emacs and Vim
> to have a third-party mode for editing CSV data with a tabular
> interface.
> 
> 
> Indeed, such modes exist; one that I found immediately for Emacs is
> http://www.emacswiki.org/emacs/csv-mode.el>. Has anyone got a good
> Emacs mode for editing CSV data as a table and saving it back to CSV
> data?


Emacs users can have the cake and eat it too; ie use spreadsheet
functionality without having to use a separate spreadsheet file
and software.

The basic idea is to use org-mode which has a table
editor with spreadsheet functionality while continuing to live within a 
plain text editor.

It allows to edit a table entirely written in plain text in a visually 
appealing and clean way, while keeping a (less readable) python data
structure in sync with it.

The example file is below the ---

Caveats:
The orig_table string is there only make the source for the table.
The name orig_table is not necessary; a naked triple-string will also work.
The triple string is there to pacify python in the face of non valid syntax.
Ideal would have been comments but python does not have multiline comments

The table between the #BEGIN RECEIVE ORGTBL marks
and the #END RECEIVE ORGTBL marks
is the target or the recipient for the transformed version of the
plain text table.

Experiment as follows:
1. Save the stuff below - as something.py
2. Start editing the file in emacs

3. Join the 3 lines into 1 line with single space separators.
 +ORGTBL: SEND marks orgtbl-to-generic
  :lfmt "  \"%s\": [%s,%s,%s,%s,%s],"
  :llfmt "  \"%s\": [%s,%s,%s,%s,%s]"

   [It has to be one line, but if I kept it one line, it
   will be randomly be garbled in the mail!]

 This line gives the table a name ("marks") so that you can use
 several tables in one file, and it specifies how the syntax should
 be changed when syncing the python version of  the table data.

4. Start orgtbl minor mode with M-x orgtbl-mode
   Mode line should show python and orgtbl

5. Delete the contents (keep the 2 # lines intact) of the python table

6. Place cursor within the orig_table and 'send' it as follows

7. Send is done with any one of 'C-c C-c' or 'C-u C-c C-c' or 'C-u C-u C-c C-c'
   The first just sends the table as is
   The second recomputes the formulas top-down and then sends
   The third recomputes until fixpoint (you really should not be making such a  
   table!!)

8. Play with the table editor by using TAB and S-TAB to
   walk through fields and change them, use C-u C-c C-c again to
   sync the python version of the table

9. In case the above does now work (if your orgmode is too old)
   the orig_table_2 should hopefully work even for older org versions
   It furthermore shows the ability to skip columns and to format
   column widths to convenience.

--
orig_table = """

#+ORGTBL: SEND marks orgtbl-to-generic
:lfmt "  \"%s\": [%s,%s,%s,%s,%s],"
:llfmt "  \"%s\": [%s,%s,%s,%s,%s]"
| abe|  1 |  2 |  3 |  4 |10 |
| beth   |  9 |  1 |  5 |  9 |24 |
| catherine |  5 |  6 |  7 |  5 |23 |
#+TBLFM: $6=$2+$3+$4+$5
"""

stud_db = {
# Dont handedit
# BEGIN RECEIVE ORGTBL marks
  "abe": [1,2,3,4,10],
  "beth": [9,1,5,9,24],
  "catherine": [5,6,7,5,23]
# END RECEIVE ORGTBL marks
}

## In case the above does not work (if org-version too old)

orig_table_2 = """

#+ORGTBL: SEND marks2 orgtbl-to-csv :skip 2
| Name   | T1 | T2 | T3 | T4 | Total |
| <6>|||||   |
| abe|  1 |  2 |  3 |  4 |10 |
| beth   |  9 |  1 |  5 |  9 |24 |
| catherine |  5 |  6 |  7 |  5 |23 |
#+TBLFM: $6=$2+$3+$4+$5
"""

stud_db_2 = {
# Dont handedit
# BEGIN RECEIVE ORGTBL marks2
abe,1,2,3,4,10
beth,9,1,5,9,24
catherine,5,6,7,5,23
# END RECEIVE ORGTBL marks2
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: semicolon at end of python's statements

2013-09-03 Thread Neil Cerutti
On 2013-09-02, Roy Smith  wrote:
> In article ,
>  "albert visser"  wrote:
>
>> I like being able to do e.g.
>> 
>>  with open('some_file') as _in, open('another_file', 'w') as _out:
>
> It would be nice if you could write that as:
>
>   with open('some_file'), open('another_file, 'w') as _in, _out:

3.2 and above provide contextlib.ExitStack, which I just now
learned about.

with contextlib.ExitStack() as stack:
_in = stack.enter_context(open('some_file'))
_out = stack.enter_context(open('another_file', 'w'))

It ain't beautiful, but it unfolds the nesting and gets rid of
the with statement's line-wrap problems.

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


Re: How to split with "\" character, and licence copyleft mirror of ©

2013-09-03 Thread random832
On Tue, Sep 3, 2013, at 6:31, Tim Chase wrote:
> I'd contend that the two primary purposes of raw strings (this is
> starting to sound like a Spanish Inquisition sketch) are regexes and
> DOS/Win32 file path literals.  And I hit this trailing-backslash case
> all the time, as Vim's path-completion defaults to putting the
> trailing backslash at the end.  So I might be entering a literal like
> 
>   r"c:\win
> 
> and hit  which expands to
> 
>   r"c:\Windows\
> 
> for which I then need to both remove the backslash and close the
> quote.  If Python's parser just blithely ignored terminal
> backslashes, I could just close the quote and get on with my day.

Of course, in 99% of situations where you can use a windows pathname in
Python, you are free to use it with a forward slash instead of a
backslash. The fact that you're using vim's file completion, which
automatically normalizes the path separator, is why you're running into
this issue when other people may not.

Maybe enabling the 'shellslash' option (which changes it to use forward
slash) will help you, though you should be aware this also affects the
expansion of the % variable, even in the :! command, which can cause
problems with certain usage patterns.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: semicolon at end of python's statements

2013-09-03 Thread Neil Cerutti
On 2013-09-03, Neil Cerutti  wrote:
> 3.2 and above provide contextlib.ExitStack, which I just now
> learned about.
>
> with contextlib.ExitStack() as stack:
> _in = stack.enter_context(open('some_file'))
> _out = stack.enter_context(open('another_file', 'w'))
>
> It ain't beautiful, but it unfolds the nesting and gets rid of
> the with statement's line-wrap problems.

It just occurred to me that in most of my use cases ExitStack
saves me from coming up with a name for the file objects at all,
since they are needed only to make csv objects.

Here's a csv file transformer pattern:

import contextlib
import csv

import transform

with contextlib.ExitStack() as stack:
reader = csv.DictReader(stack.enter_context(open('some_file', newline='')))
writer = csv.DictWriter(
stack.enter_context(open('another_file', 'w', newline='')),
fieldnames=reader.fieldnames)
writer.writeheader()
for record in reader:
writer.writerow(transform.transform(record))

Too bad it's so dense looking.

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


Re: PyPi Module Removal

2013-09-03 Thread Skip Montanaro
> I don't really have any way to contact the author of the module.  Is there
> any way to have this deleted/renamed?

Not directly, but I opened a ticked in the PyPI bug tracker.

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


Re: can't find win32api from embedded pyrun call

2013-09-03 Thread David M. Cotter
I find i'm having this problem, but the solution you found isn't quite specific 
enough for me to be able to follow it. 

I'm embedding Python27 in my app.  I have users install ActivePython27 in order 
to take advantage of python in my app, so the python installation can't be 
touched as it's on a user's machine.

When I attempt to do:
>import win32api

i get this:
>Traceback (most recent call last):
>  File "startup.py", line 5, in 
>ImportError: DLL load failed: The specified module could not be found.

I someone suggested i manually load the dependent libraries in the correct 
order, like this:

>import pywintypes
>import pythoncom
>import win32api

but then i get this:
>Traceback (most recent call last):
>  File "startup.py", line 3, in 
>  File "C:\Python27\lib\site-packages\win32\lib\pywintypes.py", line 124, in 
> 
>__import_pywin32_system_module__("pywintypes", globals())
>  File "C:\Python27\lib\site-packages\win32\lib\pywintypes.py", line 64, in 
> __import_pywin32_system_module__
>import _win32sysloader
ImportError: DLL load failed: The specified module could not be found.

the ultimate goal here is actually to do this:
>from win32com.client.gencache import EnsureDispatch

which currently yields:
>Traceback (most recent call last):
>  File "startup.py", line 3, in 
>  File "C:\Python27\lib\site-packages\win32com\__init__.py", line 5, in 
> 
>import win32api, sys, os
>ImportError: DLL load failed: The specified module could not be found.

So, if anyone has any idea, that would be super duper great.  thanks so much!

notes: my paths are definitely set correctly
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyPi Module Removal

2013-09-03 Thread Joel Goldstick
On Tue, Sep 3, 2013 at 4:52 PM, Joel Goldstick  wrote:
> On Tue, Sep 3, 2013 at 4:15 PM, Brian Rak  wrote:
>> I was trying to install wxPython earlier today.  Not RTFMing, I tried
>> 'easy_install wx', which ended up installing this strange module:
>> https://pypi.python.org/pypi/wx
>>
>> Looking at the download stats, it seems to be confusing ~1000 users a month,
>> while not providing any significant functionality.
>>
>> I don't really have any way to contact the author of the module.  Is there
>> any way to have this deleted/renamed?
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> Joel Goldstick
> http://joelgoldstick.com

Sorry for empty mail. You can use pip:

pip uninstall 



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyPi Module Removal

2013-09-03 Thread Terry Reedy

On 9/3/2013 4:15 PM, Brian Rak wrote:

I was trying to install wxPython earlier today.  Not RTFMing, I tried
'easy_install wx', which ended up installing this strange module:
https://pypi.python.org/pypi/wx

Looking at the download stats, it seems to be confusing ~1000 users a
month, while not providing any significant functionality.

I don't really have any way to contact the author of the module.  Is
there any way to have this deleted/renamed?


There is a PyPI/catalog mailing list, which I believe is the one 
mirrored as gmane.comp.python.org at news.gmane.com. However, the PyPI
admins are reluctant to unilaterally delete a package. They might try to 
contact the owner of 'wx'. To bad wcPython did not grab the abbreviation.


--
Terry Jan Reedy

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


Re: PyPi Module Removal

2013-09-03 Thread Brian Rak

Thanks! Wasn't really sure where I should have reported that.

On 9/3/2013 4:56 PM, Skip Montanaro wrote:

I don't really have any way to contact the author of the module.  Is there
any way to have this deleted/renamed?

Not directly, but I opened a ticked in the PyPI bug tracker.

Skip


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


Re: PyPi Module Removal

2013-09-03 Thread Joel Goldstick
On Tue, Sep 3, 2013 at 4:15 PM, Brian Rak  wrote:
> I was trying to install wxPython earlier today.  Not RTFMing, I tried
> 'easy_install wx', which ended up installing this strange module:
> https://pypi.python.org/pypi/wx
>
> Looking at the download stats, it seems to be confusing ~1000 users a month,
> while not providing any significant functionality.
>
> I don't really have any way to contact the author of the module.  Is there
> any way to have this deleted/renamed?
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: to be pythonic: should caller or callee log?

2013-09-03 Thread Terry Reedy

On 9/3/2013 12:07 PM, Gildor Oronar wrote:

What would you choose? Do you put logging routine into caller or callee?
My intuitive answer is "callee does the logging, because that's where
action takes place", like this:

class Account():
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))
 ...

if '__name__' == '__main__'
 
 account.transaction(amount, target)


Simple and easy. Put logging code to the caller would be tedious - the
function is called about 20 times in different places.

So far so good, but we grew up to have 10 different account classes:

class AbsctractAccount():

class CreditAccount(AbstractAccount):
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))
 ...

class DebitAccount(AbstractAccount):
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))
 ...

class SomeOtherAccount(...)
 

Then letting the callee do the logging is also tedious now.

What is the best practise here?

If, for the convenience, we define transaction function in
AbstractAccount to just do the logging, and change inherited classes,
like this:

class AbsctractAccount():
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))

class DebitAccount(AbstractAccount):
 def transaction(self, amount, target):
 super().transaction(amount,target)
 

Then we gethered logging code pieces all to one place, but it begets two
other problems.

1. It is a "surprise" that super().transaction must be called first,


Not to me ;-). That is fairly standard in super examples I have seen posted.

> not last, and that it does only the logging.

If that is the only thing in common ...


2. The code used to check whether "transaction" is implemented:

>  if hasAttr(DebitAccount, 'transaction'): # clear to read

has to be changed to check whether "transaction" is inherited:
 if not DebitAccount.transaction is AbstractAccount.transaction:

whose purpose is confusing, and whose cause is a little surprise too.


I would expect that every account class has a transaction method.
* If so, just call it, but
assertIsNot(DebitAccount.transaction, AbstractAccount.transaction)
for every subclass in your test suite.
* If not, perhaps you need an abstract subclass TransAccount. Then use 
hasattr in production code and the isnot test in test code.




Also, the pythonic "boldly calling and watching for exception" stopped
working, because instead of getting AttributeError, we would get a line
of log and nothing more.


This is what test suites are for.

--
Terry Jan Reedy

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


PyPi Module Removal

2013-09-03 Thread Brian Rak
I was trying to install wxPython earlier today.  Not RTFMing, I tried 
'easy_install wx', which ended up installing this strange module: 
https://pypi.python.org/pypi/wx


Looking at the download stats, it seems to be confusing ~1000 users a 
month, while not providing any significant functionality.


I don't really have any way to contact the author of the module.  Is 
there any way to have this deleted/renamed?

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


unbound method () must be called with ... instance as first argument (got nothing instead)

2013-09-03 Thread Mohsen Pahlevanzadeh
Dear all,

I have the following two lines code in my setup frame:
 // 
 self.showHideConstructor = ui.interface.interface.ShowHide()
 QtCore.QObject.connect(self.pushButtonAdd,
QtCore.SIGNAL(_fromUtf8("clicked()")),self.showHideConstructor,ui.interface.interface.ShowHide.showFindMaterials())
//

and i have module ui.interface.interface , it contains ShowHide class,
and it consists showFindMaterials() method.

When i run program , i get the following traceback :
///
Traceback (most recent call last):
  File "./main.py", line 113, in 
main()
  File "./main.py", line 94, in main
interfaceObj.showMaterials()
  File "/home/mohsen/codes/amlak/amlak/src/ui/interface/interface.py",
line 82, in showMaterials
self.ui.setupUi(self.Frame)
  File "/home/mohsen/codes/amlak/amlak/src/ui/materialsFrame.py", line
92, in setupUi
QtCore.QObject.connect(self.pushButtonAdd,
QtCore.SIGNAL(_fromUtf8("clicked()")),self.showHideConstructor,ui.interface.interface.ShowHide.showFindMaterials())
TypeError: unbound method showFindMaterials() must be called with
ShowHide instance as first argument (got nothing instead)
///

Where's problem?



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


Re: unbound method () must be called with ... instance as first argument (got nothing instead)

2013-09-03 Thread Mohsen Pahlevanzadeh
Solved, i changed my connect function to:
QtCore.QObject.connect(self.pushButtonAdd,
QtCore.SIGNAL(_fromUtf8("clicked()")),self.showHideConstructor.showFindMaterials)
On Wed, 2013-09-04 at 02:00 +0430, Mohsen Pahlevanzadeh wrote:
> Dear all,
> 
> I have the following two lines code in my setup frame:
>  // 
>  self.showHideConstructor = ui.interface.interface.ShowHide()
>  QtCore.QObject.connect(self.pushButtonAdd,
> QtCore.SIGNAL(_fromUtf8("clicked()")),self.showHideConstructor,ui.interface.interface.ShowHide.showFindMaterials())
> //
> 
> and i have module ui.interface.interface , it contains ShowHide class,
> and it consists showFindMaterials() method.
> 
> When i run program , i get the following traceback :
> ///
> Traceback (most recent call last):
>   File "./main.py", line 113, in 
> main()
>   File "./main.py", line 94, in main
> interfaceObj.showMaterials()
>   File "/home/mohsen/codes/amlak/amlak/src/ui/interface/interface.py",
> line 82, in showMaterials
> self.ui.setupUi(self.Frame)
>   File "/home/mohsen/codes/amlak/amlak/src/ui/materialsFrame.py", line
> 92, in setupUi
> QtCore.QObject.connect(self.pushButtonAdd,
> QtCore.SIGNAL(_fromUtf8("clicked()")),self.showHideConstructor,ui.interface.interface.ShowHide.showFindMaterials())
> TypeError: unbound method showFindMaterials() must be called with
> ShowHide instance as first argument (got nothing instead)
> ///
> 
> Where's problem?
> 
> 
> 


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


Conflict between Python 2.5 and 2.7

2013-09-03 Thread Errol Anderson
I look after a Delphi program that uses Python 2.5 (via Python for Delphi).
A customer who uses a modeling program that requires Python 2.7 experiences
a Python conflict when trying to run the Delphi program.  I have installed
both Python 2.5 and 2.7 on a test-bed computer and can run the Delphi
program.  I have searched the FAQ, and have found some mention of being able
to set a default Python version when installing, which I presume has
occurred when the customer installed Python 2.7, so that the Delphi program
is being directed to Python 2.7.

 

However, I do not see this option when I install Python 2.7, and I do not
see how to remove this option so I can advise the customer what to do.  The
programs are running under Windows 7 - 32-bit.   Any assistance gratefully
received.

 

Best regards

 

Errol Anderson

 

 

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


Re: Cannot form correctly the FORM part of the header when sending mail

2013-09-03 Thread Piet van Oostrum
Ferrous Cranus  writes:

> Hello,
> i have written the following snipper of code to help me send mail:
>

[snip]

> # prepare mail data
> TO = "[email protected]"
>
> SUBJECT = u"Mail από τον επισκέπτη: ( %s )" % FROM
>
> MESSAGE = "From: %s\r\n" + "To: %s\r\n" + "Subject: %s\r\n"
> + MESSAGE + "\r\n"
> MESSAGE = MESSAGE % ( FROM, TO, SUBJECT )
> MESSAGE = MESSAGE.encode('utf-8')

First a couple of remarks:
1. You should add an empty line between the headers and the message (I
suppose the message does not start with an empty line).
2. It is better to do the % substitution only on the headers, not
including the message, just in case the message contains a % sign.
That makes it:
 MESSAGE = "From: %s\r\n" + "To: %s\r\n" + "Subject: %s\r\n\r\n" % 
  ( FROM, TO, SUBJECT ) + MESSAGE + "\r\n"
 MESSAGE = MESSAGE.encode('utf-8')
3. It is bad coding style in Python to use all-caps variables. Better
use message instead of MESSAGE etc.

[snip]

> It works as expected, but the the problem is that it display the FROM
> part as being send from ,my personal GMail account when it supposed to
> be shown the format variable field that was passed by index.html to the
> mail.py script.

Where does it display that?
Do you happen to read that mail in a Microsoft program?
If yes, then it is the fault of that program. Read the mail in some
other program and you will probably see that the proper From address is
there.

The problem is that Gmail inserts a "Sender" header with your account
(email address) and certain Microsoft programs use that to display as
the From address instead of the real From address. It's against the
rules, but then, Microsoft makes its own rules and who is going to stop
them?

And maybe there are other mail programs that do the same. AFAIK there is
no way to get rid of that Sender line.
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyPi Module Removal

2013-09-03 Thread Steven D'Aprano
On Tue, 03 Sep 2013 16:15:07 -0400, Brian Rak wrote:

> I was trying to install wxPython earlier today.  Not RTFMing, I tried
> 'easy_install wx', which ended up installing this strange module:
> https://pypi.python.org/pypi/wx
> 
> Looking at the download stats, it seems to be confusing ~1000 users a
> month, while not providing any significant functionality.

Ah, Unix users. Who else would imagine that the way to install something 
called "wxPython" was to use "install wx"?

:-)



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


Re: to be pythonic: should caller or callee log?

2013-09-03 Thread Ethan Furman

On 09/03/2013 09:07 AM, Gildor Oronar wrote:

What would you choose? Do you put logging routine into caller or callee? My 
intuitive answer is "callee does the
logging, because that's where action takes place", like this:

class Account():
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))
 ...

So far so good, but we grew up to have 10 different account classes:

class AbsctractAccount():

class CreditAccount(AbstractAccount):
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))
 ...

class DebitAccount(AbstractAccount):
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))
 ...

class SomeOtherAccount(...)
 

Then letting the callee do the logging is also tedious now.

What is the best practise here?

If, for the convenience, we define transaction function in AbstractAccount to 
just do the logging, and change inherited
classes, like this:

class AbsctractAccount():
 def transaction(self, amount, target):
 logging.info("Start transaction of %s to %s" % (amount, target))

class DebitAccount(AbstractAccount):
 def transaction(self, amount, target):
 super().transaction(amount,target)
 


In this instance you're not really gaining anything by using inheritance: before you had one line for logging, after you 
have one line to call super(); in either case if you forget the one line you don't get a log entry.


I would say it is not really the caller's or the callee's job to do the logging, even though it should be done.  What 
would be really handy is a function that sat in between the caller and callee that logged for you -- you know, a decorator:


# not tested, but hopefully you get the idea
def log(func):
def wrapper(*args, **kwds):
text = []
if args:
text.append(str(args))
if kwds:
text.append(str(kwds))
text = ', '.join(text)
if text:
logging.info("%s called with %s" % (func.__name__, text)
else:
logging.info("%s called" % func.__name__)
return func(*args, **kwds)
return wrapper

Then you can say:

 class WhateverAccount:

@log
def transaction(self, amount, target):
...

True, you still one line, but moves the logging concern outside the function, where it doesn't really belong.  It also 
makes it really easy to see if a function will be logged or not.


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


Re: PyPi Module Removal

2013-09-03 Thread Skip Montanaro
> Ah, Unix users. Who else would imagine that the way to install something
> called "wxPython" was to use "install wx"?

I'm not a wxPython user, but it seems the package/module you import in your
programs is "wx". Not an unreasonable guess at the PyPI package name.

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


Re: PyPi Module Removal

2013-09-03 Thread Brian Rak


On 9/3/2013 10:49 PM, Skip Montanaro wrote:



> Ah, Unix users. Who else would imagine that the way to install something
> called "wxPython" was to use "install wx"?

I'm not a wxPython user, but it seems the package/module you import in 
your programs is "wx". Not an unreasonable guess at the PyPI package name.


Skip



Yep, that was my thinking entirely.  'import wx' = 'pip install wx'.  
Seems perfectly logical to me.

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


Re: can't find win32api from embedded pyrun call

2013-09-03 Thread David M. Cotter
note that when the script is called, i DO see this in the output window:

> 'kJams 2 Debug.exe': Loaded 'C:\Python27\Lib\site-packages\win32\win32api.pyd'
> 'kJams 2 Debug.exe': Loaded 'C:\Windows\SysWOW64\pywintypes27.dll'
> 'kJams 2 Debug.exe': Unloaded 
> 'C:\Python27\Lib\site-packages\win32\win32api.pyd'
> 'kJams 2 Debug.exe': Unloaded 'C:\Windows\SysWOW64\pywintypes27.dll'
-- 
https://mail.python.org/mailman/listinfo/python-list


Beginner's guide to Python

2013-09-03 Thread Steve Hayes
Can anyone recommend a web site that gives a good beginner's guide to Python?

One that tells one, especially --

-- what kind of projects Python is good for 
-- what kind of projects it is not good for
-- a simple explanation of how it works
-- a kind of beginner's tutotial and guide to its syntax

I've read about Python, and installed it on my computer when I found it on a
DVD that came with a magazine, but I haven't got a clue about how to use it.

So any advice on the best web sites for absolute novices would be welcome. 


-- 
Steve Hayes from Tshwane, South Africa
Blog: http://khanya.wordpress.com
E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk
-- 
https://mail.python.org/mailman/listinfo/python-list


how to detect comment in source code file ?

2013-09-03 Thread vnkumbhani
how works python interpreter for finding comment ?
if possible find nested comment ?
-- 
https://mail.python.org/mailman/listinfo/python-list


how does not work nested comment in python?

2013-09-03 Thread vnkumbhani
example: 
 
print "hello" # print comment +"world"=> single line comment
print "hello" '''print comment''' +"world"   => multiple line comment
-- 
https://mail.python.org/mailman/listinfo/python-list