newbie ``print`` question

2012-09-02 Thread gwhite
I can't figure out how to stop the "add a space at the beginning"
behavior of the print function.

>>> print 1,;print 2,
1 2

See the space in between the 1 and the 2 at the output print to the
command console?

The help for print is:

"A space is written before each object is (converted and) written,
unless the output system believes it is positioned at the beginning of
a line."

So it is apparently doing what it is supposed to do.

Is there a way to stop this?  Or is there a different function that
will only print what you have in the formatted string?

For example, in MATLAB I only had to do:

>> fprintf('1');fprintf('2')
12

 fprintf works the same way if printing to a file.  It only puts in
what you explicitly tell it to put in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 10:49 am, mblume  wrote:
> Am Sun, 02 Sep 2012 10:23:53 -0700 schrieb gwhite:
>
>
>
>
>
>
>
>
>
> > I can't figure out how to stop the "add a space at the beginning"
> > behavior of the print function.
>
> >>>> print 1,;print 2,
> > 1 2
>
> > See the space in between the 1 and the 2 at the output print to the
> > command console?
>
> > The help for print is:
>
> > "A space is written before each object is (converted and) written,
> > unless the output system believes it is positioned at the beginning of a
> > line."
>
> > So it is apparently doing what it is supposed to do.
>
> > Is there a way to stop this?  Or is there a different function that will
> > only print what you have in the formatted string?
>
> > For example, in MATLAB I only had to do:
>
> >>> fprintf('1');fprintf('2')
> > 12
>
> >  fprintf works the same way if printing to a file.  It only puts in
> > what you explicitly tell it to put in.
>
> import sys
>
> sys.stdout.write("1"); sys.stdout.write("2")
>
> HTH
> Martin

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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 10:55 am, Chris Rebert  wrote:
> On Sun, Sep 2, 2012 at 10:23 AM, gwhite  wrote:
> > I can't figure out how to stop the "add a space at the beginning"
> > behavior of the print function.
>
> >>>> print 1,;print 2,
> > 1 2
>
> > See the space in between the 1 and the 2 at the output print to the
> > command console?
>
> > The help for print is:
>
> > "A space is written before each object is (converted and) written,
> > unless the output system believes it is positioned at the beginning of
> > a line."
>
> > So it is apparently doing what it is supposed to do.
>
> > Is there a way to stop this?
>
> If you were to use Python 3.x, yes. Otherwise, no.
>
> > Or is there a different function that
> > will only print what you have in the formatted string?
>
> Use the .write() method of the sys.stdout file 
> object.http://docs.python.org/library/sys.html#sys.stdout
>
> Alternatively, you can stick with `print` and rework your code so that
> it outputs an entire line at a time (thus, there'd only be 1 argument
> passed to `print`, so its "spaces between arguments" feature wouldn't
> come into play).
>
> Cheers,
> Chris

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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 11:33 am, Terry Reedy  wrote:
> On 9/2/2012 1:23 PM, gwhite wrote:
>
> > I can't figure out how to stop the "add a space at the beginning"
> > behavior of the print function.
>
> >>>> print 1,;print 2,
> > 1 2
>
> You have discovered why print is a function in 3.x.
>  >>> print(1, 2, sep='')
> 12
>  >>> print(1, end=''); print(2, end='')
> 12
>
> In 2.6 or 2.7, you can add
>    from __future__ import print_function
> but I recommend using 3.2 or 3.3 unless you have a reason to use older
> Python.
>
> --
> Terry Jan Reedy

Thanks.  I would use 3.2 or 3.3, but I am actually using pythonxy,
which hasn't quite gotten there yet, as the bundle of packages has to
all play nice together. Or so I am guessing.   I have been considering
the __future__ technique.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 10:55 am, Chris Rebert  wrote:
> On Sun, Sep 2, 2012 at 10:23 AM, gwhite  wrote:
> > I can't figure out how to stop the "add a space at the beginning"
> > behavior of the print function.
>
> >>>> print 1,;print 2,
> > 1 2
>
> > See the space in between the 1 and the 2 at the output print to the
> > command console?
>
> > The help for print is:
>
> > "A space is written before each object is (converted and) written,
> > unless the output system believes it is positioned at the beginning of
> > a line."
>
> > So it is apparently doing what it is supposed to do.
>
> > Is there a way to stop this?
>
> If you were to use Python 3.x, yes. Otherwise, no.
>
> > Or is there a different function that
> > will only print what you have in the formatted string?
>
> Use the .write() method of the sys.stdout file 
> object.http://docs.python.org/library/sys.html#sys.stdout
>
> Alternatively, you can stick with `print` and rework your code so that
> it outputs an entire line at a time (thus, there'd only be 1 argument
> passed to `print`, so its "spaces between arguments" feature wouldn't
> come into play).

On the "rework" thing, yes, I suppose I could construct the line as a
single string prior to print.There would be things like `for`
loops and conditionals to do so.  That isn't so unusual.

I was actually doing some simple tests of other things -- you know,
newbie stuff to make sure I understood what the various ops were
doing.  I wasn't even thinking about `print` Then I got sidetracked
with this item, which I thought was very odd, since it is "deciding
for you" to stuff a space in.

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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 12:26 pm, gwhite  wrote:
> On Sep 2, 10:55 am, Chris Rebert  wrote:
>
>
>
>
>
>
>
>
>
> > On Sun, Sep 2, 2012 at 10:23 AM, gwhite  wrote:
> > > I can't figure out how to stop the "add a space at the beginning"
> > > behavior of the print function.
>
> > >>>> print 1,;print 2,
> > > 1 2
>
> > > See the space in between the 1 and the 2 at the output print to the
> > > command console?
>
> > > The help for print is:
>
> > > "A space is written before each object is (converted and) written,
> > > unless the output system believes it is positioned at the beginning of
> > > a line."
>
> > > So it is apparently doing what it is supposed to do.
>
> > > Is there a way to stop this?
>
> > If you were to use Python 3.x, yes. Otherwise, no.
>
> > > Or is there a different function that
> > > will only print what you have in the formatted string?
>
> > Use the .write() method of the sys.stdout file 
> > object.http://docs.python.org/library/sys.html#sys.stdout
>
> > Alternatively, you can stick with `print` and rework your code so that
> > it outputs an entire line at a time (thus, there'd only be 1 argument
> > passed to `print`, so its "spaces between arguments" feature wouldn't
> > come into play).
>
> On the "rework" thing, yes, I suppose I could construct the line as a
> single string prior to print.    There would be things like `for`
> loops and conditionals to do so.  That isn't so unusual.
>
> I was actually doing some simple tests of other things -- you know,
> newbie stuff to make sure I understood what the various ops were
> doing.  I wasn't even thinking about `print` Then I got sidetracked
> with this item, which I thought was very odd, since it is "deciding
> for you" to stuff a space in.

btw, I also thought the default "add a CR LF" to the end was odd too.
But at least that one had a simple way out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 10:45 am, Joel Goldstick  wrote:
> On Sun, Sep 2, 2012 at 1:23 PM, gwhite  wrote:
> > I can't figure out how to stop the "add a space at the beginning"
> > behavior of the print function.
>
> >>>> print 1,;print 2,
> > 1 2
>
> > See the space in between the 1 and the 2 at the output print to the
> > command console?
>
> > The help for print is:
>
> > "A space is written before each object is (converted and) written,
> > unless the output system believes it is positioned at the beginning of
> > a line."
>
> > So it is apparently doing what it is supposed to do.
>
> > Is there a way to stop this?  Or is there a different function that
> > will only print what you have in the formatted string?
>
> You can do it with string formatting.  My example shows 'old style'
> string formatting syntax.  There is a newer style.  You can learn
> about both from the online python docs.
>
>
>
> >>> print "%d%d" % (1,2)
> 12

For "real" stuff, I've been trying to use that.  I saw it in Beazley's
latest Essential text.

You're right, I can construct a single string and then write it.  In
fact, it looks like it is a must unless using the 3.2/3.3 version of
`print`.

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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 12:43 pm, Dave Angel  wrote:
> On 09/02/2012 03:34 PM, gwhite wrote:
>
> > 
>
> > btw, I also thought the default "add a CR LF" to the end was odd too.
> > But at least that one had a simple way out.
>
> But it (print on Python 2.x) doesn't, unless you're stuck on Windows.
> And even then, you can prevent it by using a 'b' in the mode.

Yes, I'm using windows.  What is "'b' in the mode?"  The help for
print says:

A ``'\n'`` character is written at the end, unless the ``print``
statement ends with a comma.  This is the only action if the statement
contains just the keyword ``print``.

So I followed with a comma to stop the default CR LF insertion.

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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 11:33 am, Terry Reedy  wrote:
> On 9/2/2012 1:23 PM, gwhite wrote:
>
> > I can't figure out how to stop the "add a space at the beginning"
> > behavior of the print function.
>
> >>>> print 1,;print 2,
> > 1 2
>
> You have discovered why print is a function in 3.x.
>  >>> print(1, 2, sep='')
> 12
>  >>> print(1, end=''); print(2, end='')
> 12
>
> In 2.6 or 2.7, you can add
>    from __future__ import print_function
> but I recommend using 3.2 or 3.3 unless you have a reason to use older
> Python.

It looks like one can avoid pre-construction of the total line with
3.x.

>>> from __future__ import print_function
>>> print('a=%.1f,' % 1.0, end='');print('b=%.1f' % 2.0, end='')
a=1.0,b=2.0

Thanks.  It isn't that hard to pre-construct, but regardless, there is
better control in 3.x.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 1:16 pm, Dave Angel  wrote:
> On 09/02/2012 03:50 PM, gwhite wrote:
>
>
>
>
>
>
>
>
>
> > On Sep 2, 12:43 pm, Dave Angel  wrote:
> >> On 09/02/2012 03:34 PM, gwhite wrote:
>
> >>> 
> >>> btw, I also thought the default "add a CR LF" to the end was odd too.
> >>> But at least that one had a simple way out.
> >> But it (print on Python 2.x) doesn't, unless you're stuck on Windows.
> >> And even then, you can prevent it by using a 'b' in the mode.
> > Yes, I'm using windows.  What is "'b' in the mode?"  The help for
> > print says:
>
> > A ``'\n'`` character is written at the end, unless the ``print``
> > statement ends with a comma.  This is the only action if the statement
> > contains just the keyword ``print``.
>
> > So I followed with a comma to stop the default CR LF insertion.
>
> You're correct;  the best way to suppress the newline at the end of
> print is to use the trailing comma.  But since print is for lines, it
> usually is a good default.  If you don't want to get any extra
> characters, just use write().  It takes a string, and outputs exactly
> what it's given.
>
> I assumed you were complaining about the conversion of newline to
> carriage-return-newline, which is done by default on Windows, and can be
> suppressed by opening the file with "b" as the mode parameter.


Sorry, I was a little vague on the newline stuff.

In any case, I've learned I should probably avoid the comma, if
looking at 3.x:

>>> from __future__ import print_function
>>> print('a=%.1f,' % 1.0),;print('b=%.1f' % 2.0)
a=1.0,
(None,)
b=2.0

Given the input of several posters, I feel like I should probably be
using the `write` function anyway.   (I don't have a problem pre-
constructing strings either.)

But I am a newbie, and "all" the show-and-tell examples/tutorials use
`print`.  But this little thread has helped me a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 1:37 pm, Dennis Lee Bieber  wrote:
> On Sun, 2 Sep 2012 10:23:53 -0700 (PDT), gwhite 
> declaimed the following in gmane.comp.python.general:
>
>
>
> > "A space is written before each object is (converted and) written,
> > unless the output system believes it is positioned at the beginning of
> > a line."
>
> > So it is apparently doing what it is supposed to do.
>
> > Is there a way to stop this?  Or is there a different function that
> > will only print what you have in the formatted string?
>
> E:\UserData\Wulfraed\My Documents>python
> ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
> Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> >>> import sys
> >>> print "1",;sys.stdout.softspace=0;print "2"
> 12
>
> >>> sys.stdout.write("1");sys.stdout.write("2");print
> 12
>
>         In Python 2.x, the equivalent of fprint/fprintf is NOT print but
> sys.stdout.write/file_object.write
>
>         "print" is just a convenience function that is designed to translate
> its arguments into a textual representation, and then drop it to the
> screen. Part of the convenience is to separate output items by a space
> and to emit a newline at the end.
>
>         .write(), OTOH, does no formatting -- not even new lines. You have
> to provide all conversion to text, and line endings.

Thanks.  I am starting to get it.

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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 1:49 pm, Terry Reedy  wrote:
> On 9/2/2012 3:26 PM, gwhite wrote:
>
> > On the "rework" thing, yes, I suppose I could construct the line as a
> > single string prior to print.    There would be things like `for`
> > loops and conditionals to do so.  That isn't so unusual.
>
> The usual idiom is to construct a list of pieces and then join with ''.
>
>  >>> print(''.join(['1', '2']))
> 12
>
> Or map str to a list of objects.
>
>  >>> print(''.join(map(str, [1, 2])))
> 12
>
> You can do either of these in 2.x.
> If you use .write, include '\n' at the end of the list (when needed).
>
> Print was designed as a quick and easy way to put lines of text on the
> screen. Then people asked for a way to use with with other streams,
> hence the >> hack. Then people wanted ways to control the separator and
> terminator. As that point, Guido realized that it needed to be a
> function, not a statement, with all the options requested.

Thanks again, Terry.  There is a lot to the language, I am finding
out.  I am a HW engineer, not really a programmer.  Python seems a lot
more sophisticated than MATLAB.

I'm kinda thinking `write` is likely to be a little more "stable" than
`print` (if that is the right characterization) when my eventual
switch from 2.7 to 3.x happens.  You think?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 2:47 pm, Chris Angelico  wrote:
> On Mon, Sep 3, 2012 at 7:18 AM, gwhite  wrote:
> > Thanks again, Terry.  There is a lot to the language, I am finding
> > out.  I am a HW engineer, not really a programmer.  Python seems a lot
> > more sophisticated than MATLAB.
>
> > I'm kinda thinking `write` is likely to be a little more "stable" than
> > `print` (if that is the right characterization) when my eventual
> > switch from 2.7 to 3.x happens.  You think?
>
> If you're planning to switch, make use of __future__. It's
> specifically to make that job easier. Once you have a future
> declaration at the top, print() will be stable across 2.7 and 3.x.

I guess you're saying 3.x will just ignore:

from __future__ import print_function

I'll risk being silly, and thus ask: but what if when I get to 3.x
there is no __future__, as it is now "present?"  Do I need to strip
out the line?

What would happen when I finally started running 3.3, and a new
__future__ was made that broke the old syntax?  Do I need to strip out
the line?

I'm probably over thinking it.  I don't know what I am doing.  lol!



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


Re: newbie ``print`` question

2012-09-02 Thread gwhite
On Sep 2, 3:43 pm, MRAB  wrote:
> On 02/09/2012 21:58, gwhite wrote:
>
>
>
>
>
>
>
> > On Sep 2, 1:16 pm, Dave Angel  wrote:
> >> On 09/02/2012 03:50 PM, gwhite wrote:
>
> >> > On Sep 2, 12:43 pm, Dave Angel  wrote:
> >> >> On 09/02/2012 03:34 PM, gwhite wrote:
>
> >> >>> 
> >> >>> btw, I also thought the default "add a CR LF" to the end was odd too.
> >> >>> But at least that one had a simple way out.
> >> >> But it (print on Python 2.x) doesn't, unless you're stuck on Windows.
> >> >> And even then, you can prevent it by using a 'b' in the mode.
> >> > Yes, I'm using windows.  What is "'b' in the mode?"  The help for
> >> > print says:
>
> >> > A ``'\n'`` character is written at the end, unless the ``print``
> >> > statement ends with a comma.  This is the only action if the statement
> >> > contains just the keyword ``print``.
>
> >> > So I followed with a comma to stop the default CR LF insertion.
>
> >> You're correct;  the best way to suppress the newline at the end of
> >> print is to use the trailing comma.  But since print is for lines, it
> >> usually is a good default.  If you don't want to get any extra
> >> characters, just use write().  It takes a string, and outputs exactly
> >> what it's given.
>
> >> I assumed you were complaining about the conversion of newline to
> >> carriage-return-newline, which is done by default on Windows, and can be
> >> suppressed by opening the file with "b" as the mode parameter.
>
> > Sorry, I was a little vague on the newline stuff.
>
> > In any case, I've learned I should probably avoid the comma, if
> > looking at 3.x:
>
> >>>> from __future__ import print_function
> >>>> print('a=%.1f,' % 1.0),;print('b=%.1f' % 2.0)
> > a=1.0,
> > (None,)
> > b=2.0
>
> Explanation:
>
> With 'print' as a function, the first 'print' prints the result of
> "'a=%.1f,' % 1.0" and then returns None. The trailing comma makes that
> into a tuple (None,), which is printed by the interactive interpreter
> as such.
>
> In other words:
>
>  >>> None,
> (None,)
>  >>>
>
> The second prints the result of "'b=%.1f' % 2.0" and then returns None.
> The interactive interpreter, recognising that it's only None, doesn't
> bother to print it.
>
> In other words:
>
>  >>> None

Thanks, that makes sense.

It does look like 2.7 & 3.3 don't parse the comma the same way.  Just
to repeat, since I didn't give the exact same line to both versions of
Python:

2.7
>>> print('a=%.1f,' % 1.0),;print('b=%.1f' % 2.0)
a=1.0, b=2.0

This has been more informative than I thought it was going to be.
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie questions on import & cmd line run

2012-05-16 Thread gwhite
Hi,

I am a newbie running the latest pythonxy (2.7.2.1) & spyder and
python 2.7.2.   I suspect my questions are mostly basic to python, and
not specific to Spyder or iPython.

Note: Up until now, I mainly used MATLAB, and thus need to de-program
myself appropriately.

I use Win7-64.

I wrote the following .py file:

-
#! 
# Filename: newbie00.py

if __name__ == '__main__':
print 'This program was called from the \
system command line.'
print __name__ + '.py'
else:
print 'This program was imported on the \
Python command line.'
print __name__ + '.py'

-

If I run from the system (win cmd) command, I get:

C:\engineer\engruser\python>python  newbie00.py

This program was called from the system command line.
__main__.py

-
If I hit the run button in Sypder, I get (in the iPython command
console):

In [70]: runfile(r'C:\engineer\engruser\python\newbie00.py', wdir=r'C:
\engineer\engruser\python')
This program was called from the system command line.
__main__.py


-
If I import on the iPython command, I get:

In [71]: import newbie00
This program was imported on the Python command line.
newbie00.py

-
If I import *again* on the iPython command, I get:

In [72]: import newbie00

In [73]:



-
If I hit the run button (again) in Sypder, I get (in the iPython
command console):

In [73]: runfile(r'C:\engineer\engruser\python\newbie00.py', wdir=r'C:
\engineer\engruser\python')
UMD has deleted: newbie00
This program was called from the system command line.
__main__.py

---

Some questions:

1.  If running from the system command line, or the Sypder "run"
button, "__name__" is "__main__" rather than "newbie00", as seen
above.

So, how would I get the file name newbie00.py in these two noted
cases?  I mean, what other function do I use to get it?  (This
functionality is something that occasionally came in handy back in my
m-file writing days.  Perhaps I am wrong in anticipating such an
occasional need, but I would not know that yet.)

2.  In python, there seems to be a distinction between running
something as if it is a system command of "C:\...>python myPyFile.py"
compared to simply entering that same ".py" file name directly on the
python console command line.  In fact, the latter does not work unless
the somewhat lengthy ">>> runfile(r'C:\... wdir=r'C:\...) stuff is
entered (in iPython).  (I mean, my old MATLAB habit of simply entering
">> mfilename" on the command line seems to be quite wrong in python.)

Is there a shortened syntax of running a .py from the python command
prompt, if not using a Spyder "run" button?  Or should I always run as
if from the system prompt?  That is, dispense with the MATLAB-like
"run from MATLAB/python command line" bias I may be holding.

3.  In injecting my old MATLAB bias of running via the command line
">> mfilename", I tried a tweak of  ">>>import newbie00".  That "sort
of" worked, but only the first time.

Why did the subsequent run of ">>>import newbie00" print nothing?  I'm
just trying to understand how python works.

4.  The final case shown of hitting the Spyder run button included
this:

UMD has deleted: newbie00

What does that mean?  I noted that after this "automatic" deletion, I
could do the ">>>import newbie00" once again and get the print.  (I
did not show that above.)

5.  I think #4 implies an import can be removed.  (Yes/No?)  I am not
sure why that would be desired, but I will ask how to remove an
import, or to "refresh" the run, of that is the appropriate question.

I think I saw someplace where a .pyc file is created on an initial run
and subsequently run instead of the .py.  I'm not sure if that applies
here, but if related, I guess an auxiliary question is how to easily
force the .py to run rather than the .pyc?

6.  Perhaps peripherally related to getting a running script/function/
module name, is getting a "call listing" of all the functions (and
modules) called by a .py program.  How would I get that?  I only ask
as it comes in handy if one distributes a program.  I mean, you only
give people what they actually need.

---
Advance thanks to any one who answers any of my questions.  I am sure
they appear from misguided to rudimentary in character.  I'm don't
claim to be a programmer; I did okay with MATLAB.  I'm trying to
bootstrap here, and appreciate any help.

Thanks!
Greg




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


Re: Newbie questions on import & cmd line run

2012-05-18 Thread gwhite
On May 16, 9:33 pm, Steven D'Aprano  wrote:
> On Wed, 16 May 2012 18:45:39 -0700, gwhite wrote:
> > #! 
> > # Filename: newbie00.py
>
> "Supposed to"? Nothing -- it is completely optional.
>
> #! ("hash-bang") lines currently do nothing on Windows machines, they are
> just comments. However, on Unix and Linux machines (and Macintosh?) they
> are interpreted by the shell (equivalent to cmd.exe or command.com), in
> order to tell the shell what interpreter to use to execute the program if
> you run it directly. It is common to use something like:
>
> #!/usr/bin/env python
>
> but I stress that this is completely optional, and doesn't do anything on
> Windows.
>
> > if __name__ == '__main__':
> >     print 'This program was called from the \
> > system command line.'
> >     print __name__ + '.py'
> > else:
> >     print 'This program was imported on the \
> > Python command line.'
> >     print __name__ + '.py'
>
> > -
>
> > If I run from the system (win cmd) command, I get:
>
> > C:\engineer\engruser\python>python  newbie00.py
>
> > This program was called from the system command line. __main__.py
>
> The magic variable "__name__" is special in Python. When you run a Python
> module as a script from the command line, it gets set to "__main__". Note
> that there is no such file "__main__.py" (unless you have happened to
> create one yourself).
>
> When you import a module, rather than run it, __name__ gets set to the
> actual filename of the module, minus the file extension.
>
> > -
> > If I hit the run button in Sypder, I get (in the iPython command
> > console):
>
> > In [70]: runfile(r'C:\engineer\engruser\python\newbie00.py', wdir=r'C:
> > \engineer\engruser\python')
> > This program was called from the system command line. __main__.py
>
> I'm not sure what Spyder is. Is it part of iPython? You may need to
> consult the iPython or Spyder docs to find out exactly what tricks it
> plays in its interactive console.

Sypder is the IDE for pythonxy.  Since some other newbies here at my
office decided to go down the pythonxy route, I wanted to be on the
same page with them.  All of us were MATLAB users.  We're engineers,
not programmers.

> > -
> > If I import on the iPython command, I get:
>
> > In [71]: import newbie00
> > This program was imported on the Python command line. newbie00.py
>
> In this case, __name__ is set to the module name (the file name less the
> file extension). Your script adds the .py at the end.
>
> > -
> > If I import *again* on the iPython command, I get:
>
> > In [72]: import newbie00
>
> > In [73]:
>
> > 
>
> That is correct. Python modules are only executed *once*, the first time
> they are imported. From then on, additional imports refer back to a
> cached module object.
>
> When you say "import newbie00", the (highly simplified!) process is this:
>
> * Python looks in sys.modules for the name "newbie00". If it finds
>   something in the cache (usually a module object), it fetches that thing
>   and assigns it to the variable "newbie00", and the import process is
>   complete.
>
> * But if it doesn't find anything in the cache, Python searches the
>   locations listed in sys.path for a module, package, or library. That
>   could mean any of:
>
>   - newbie00.py   (source code)
>   - newbie00.pyc  (compiled byte-code)
>   - newbie00.pyo  (compiled optimized byte-code)
>   - newbie00.pyw  (Windows only)
>   - newbie00.dll  (Windows only C library)
>   - newbie00.so   (Linux and Unix C library)
>
>   as well as others (e.g. packages).
>
> * If no module is found, Python raises an error, otherwise the first
>   found module is used.
>
> * If a compiled module (e.g. newbie00.pyc) is found, and is no older than
>   the source code (newbie00.py), then Python uses the pre-compiled file.
>
>   (If the compiled module is older than the source module, it is ignored.)
>
> * Otherwise Python parses the newbie00.py source code, compiles it to
>   byte-code, and writes it to the file newbie00.pyc so that the next time
>   the import will be faster.
>
> * At this point, Python now has a compiled chunk of Python byte-code.
>   It then sets the special global variable __name__ to the file name (less
>   extension), and executes that code.
>
> * If no fatal error occurs, Python now bundles the results of the
>   executed code (any function

Re: Newbie questions on import & cmd line run

2012-05-18 Thread gwhite
On May 16, 9:54 pm, alex23  wrote:
> On May 17, 11:45 am, gwhite  wrote:
>
> > 1.  If running from the system command line, or the Sypder "run"
> > button, "__name__" is "__main__" rather than "newbie00", as seen
> > above.
>
> > So, how would I get the file name newbie00.py in these two noted
> > cases?
>
> You can get it from the file name:
>
>     import os.path
>     name = os.path.split(__file__)[-1]
>
> However, you might find it better in the long term to always separate
> your code into import-only modules and execute-only scripts. It avoids
> this issue and others.

Thanks, and yes, I am starting to see your point.

> > 2.  Is there a shortened syntax of running a .py from the python command
> > prompt, if not using a Spyder "run" button?  Or should I always run as
> > if from the system prompt?  That is, dispense with the MATLAB-like
> > "run from MATLAB/python command line" bias I may be holding.
>
> Generally, the correct way of running Python code from the interpreter
> is 'import '. You might find this pattern useful:
>
> In your module:
>
>     def main(): # code goes here
>
>     if __name__ == '__main__': main()
>
> Then from the interpreter:
>
>     import mymodule; mymodule.main()

I am going to play with the idea.


> > 3.  In injecting my old MATLAB bias of running via the command line
> > ">> mfilename", I tried a tweak of  ">>>import newbie00".  That "sort
> > of" worked, but only the first time.
>
> > Why did the subsequent run of ">>>import newbie00" print nothing?  I'm
> > just trying to understand how python works.
>
> The import mechanism only imports a module once, as all files use the
> same module instance (they're effectively singletons). This happens
> with repeated imports in one module as well as across various modules
> during a single execution. So re-importing a module does nothing; to
> force a re-import, you can use the reload() function, although that
> doesn't guarantee updating all references. For example:
>
>     import mymodule
>     from mymodule import myfunc
>
>     # modify myfunc code externally
>
>     reload(mymodule)
>     myfunc() # original reference
>     mymodule.myfunc()  # newly modified function
>
> I don't think that only-one-import is true for scripts that are run
> from the command line, though. They can exist as both '__main__' and
> their actual name in the module table. (Someone please correct me if
> this understanding is wrong...)
>
> > 4.  The final case shown of hitting the Spyder run button included
> > this:
>
> > UMD has deleted: newbie00
>
> > What does that mean?  I noted that after this "automatic" deletion, I
> > could do the ">>>import newbie00" once again and get the print.  (I
> > did not show that above.)
>
> Spyder provides a convenience feature to force the reimport of user-
> defined modules, like your newbie00. After execution, it appears to
> drop all references to your module, forcing a garbage collection. As
> its no longer loaded, a subsequent import works.
>
> > 5.  I think #4 implies an import can be removed.  (Yes/No?)  I am not
> > sure why that would be desired, but I will ask how to remove an
> > import, or to "refresh" the run, of that is the appropriate question.
>
> reload()
>
> However, the only way to guarantee you've updated all references
> correctly is to close the interpreter and re-start it. For this kind
> of development process of modifying code and seeing the changes, it's
> probably better to look into writing tests instead. These will always
> be run in isolation, so you're guaranteed of having the correct
> environment each time.

I think I mostly need to revise my tact.  Some of these questions came
from my MATLAB-centric way of thinking, and I am unlearning that.

> > I think I saw someplace where a .pyc file is created on an initial run
> > and subsequently run instead of the .py.  I'm not sure if that applies
> > here, but if related, I guess an auxiliary question is how to easily
> > force the .py to run rather than the .pyc?
>
> A .pyc file won't be created for .py files that are run directly, only
> for those that are imported. You really shouldn't need to worry about
> this, though. It's an implementation detail that isn't influencing the
> issues you're seeing. However, if you do ever need to do it, you can
> stop .pyc files by passing the -B flag to the interpreter,

TeX $\times$ symbol not working in matplotlib?

2014-04-18 Thread gwhite
Hi,

I am trying to understand how to get the TeX "\times" symbol to work.  It is in 
the title() string in the code I pasted in.  The "\circ" symbol seems fine, by 
comparison.  "\times" ends up as "imes" in the figure title.

I am probably doing something dumb (hey, maybe a lot of dumb things!), but if 
you can spot and describe my mistake, I would be quite happy about that.

Thank you.

# (Using Python 2.7.5 via pythonxy.  w7-64)

--
import numpy as np
import matplotlib.pyplot as plt

Qs_rr = np.array([0.])
Qs_ri = np.array([0.])
Es_rr = np.array([-6.352844845095E-02,\
  -6.352844845095E-02,\
  -9.917112781473E-01,\
  -1.008084892264E+00,\
  -5.534164139252E-02,\
  -5.534164139252E-02])
Es_ri = np.array([ 9.329580097745E-01,\
  -9.329580097745E-01,\
   0.E+00,\
   0.E+00,\
   1.070772729531E+00,\
  -1.070772729531E+00]) 
plt.hold(False)
figs_open = plt.get_fignums()
axes_obj=plt.figure(figs_open[0]).gca()
lh1 = plt.plot(Qs_rr, Qs_ri, 'ro',\
   Es_rr, Es_ri, 'rx')
lh1[0].set_markerfacecolor('w')
lh1[0].set_markeredgecolor('r')
lh1[0].set_markersize(9.0)
lh1[0].set_markeredgewidth(0.75)
lh1[1].set_markersize(9.0)
lh1[1].set_markeredgewidth(0.75)
plt.axis([-1.2, 0.2, -1.2, 1.2])
plt.grid(True)
plt.title('$\mathrm{poles}$ $(\times)$ \
   $\mathrm{\&}$ $\mathrm{zeros}$ \
   $(\circ)$ $\mathrm{of}$ $T(s)T(-s)$',\
   fontsize=16)
plt.xlabel(r'$\sigma$', fontsize=16)
plt.ylabel(r'$\mathrm{j}\omega$', fontsize=16)
plt.show()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TeX $\times$ symbol not working in matplotlib?

2014-04-18 Thread gwhite
On Friday, April 18, 2014 9:24:55 AM UTC-7, Chris "Kwpolska" Warrick wrote:
> On Fri, Apr 18, 2014 at 6:18 PM, gwhite  wrote:
> 
> > I am trying to understand how to get the TeX "\times" symbol to work.  It 
> > is in the title() string in the code I pasted in.  The "\circ" symbol seems 
> > fine, by comparison.  "\times" ends up as "imes" in the figure title.
> >
> > I am probably doing something dumb (hey, maybe a lot of dumb things!), but 
> > if you can spot and describe my mistake, I would be quite happy about that.
> 
> > plt.title('$\mathrm{poles}$ $(\times)$ \
> >$\mathrm{\&}$ $\mathrm{zeros}$ \
> >$(\circ)$ $\mathrm{of}$ $T(s)T(-s)$',\ 
> >fontsize=16)
> 
> You're using a regular string.  In which backspaces can be used in
> escapes.  \t is one of those escapes, it is the tab character.  In
> order to fix, add the letter "r" before the opening quote.  Like this:
>  
> > plt.title(r'$\mathrm{poles}$ $(\times)$ \
> >$\mathrm{\&}$ $\mathrm{zeros}$ \
> >$(\circ)$ $\mathrm{of}$ $T(s)T(-s)$',\
> >fontsize=16)
>
> Moreover, in the next two things, you already did it right in the first place:
> 
> > plt.xlabel(r'$\sigma$', fontsize=16)
> > plt.ylabel(r'$\mathrm{j}\omega$', fontsize=16)


Thanks Chris!  That worked.

I faked myself out since the $(\circ)$ worked *without* the little r prefix. I 
was blind to it. I guess the difference must be there is no \c thingy to 
override \circ, so it just does the circle.

Thanks for the note on how the r prefix works. I knew I would screw myself 
sooner or later on that.

Getting regular text mixed with math text, but with the same font (in regular 
or italic) is a bit clumsy, I suppose. (I mean getting the spaces in.) At least 
I can do it. 

I did this too, and it also seems to work:

plt.title(' '.join([r'$\mathrm{poles}$', r'$(\times)$',\
r'$\mathrm{\&}$', r'$\mathrm{zeros}$',
r'$(\circ)$',  r'$\mathrm{of}$',\
r'$T(s)T(-s)$']), fontsize=16)

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


Re: TeX $\times$ symbol not working in matplotlib?

2014-04-18 Thread gwhite
On Friday, April 18, 2014 10:04:17 AM UTC-7, Peter Otten wrote:
> gwhite wrote:
>  
> > plt.title(' '.join([r'$\mathrm{poles}$', r'$(\times)$',\
> > r'$\mathrm{\&}$', r'$\mathrm{zeros}$',
> > r'$(\circ)$',  r'$\mathrm{of}$',\
> > r'$T(s)T(-s)$']), fontsize=16)
>  
> Note that adjacent string literals on the same line or inside parentheses 
> are automatically concatenated by the compiler. So you may write the above 
> as
>
> plt.title(
> r'$\mathrm{poles}$ $(\times)$ '
> r'$\mathrm{\&}$ $\mathrm{zeros}$ '
> r'$(\circ)$ $\mathrm{of}$ $T(s)T(-s)$',
> fontsize=16)
>  
> Even if you leave everything else as is you don't need any backslashes at 
> the end of the line.

Well even if it had been right, I omitted one (backslash). I'm such a 
newb/hack. lol.  No animals were harmed.

Yeah, I have noticed that they don't seem to be needed, but I think I remember 
reading "someplace-somewhere" that a backslash means a line continuation, and 
perhaps I saw some author put them in.  So I did it out of trying to be 
"strict."

I'm not sure when a backslash continuation might be needed, or if that 
requirement has been designed out of Python.

Anyway, thanks to all for the notes!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TeX $\times$ symbol not working in matplotlib?

2014-04-19 Thread gwhite
On Friday, April 18, 2014 8:46:13 PM UTC-7, Larry Hudson wrote:
> On 04/18/2014 04:14 PM, gwhite wrote:
> 
> > [snip]
> > I'm not sure when a backslash continuation might be needed, or if that 
> > requirement has been designed out of Python.
> 
> ['they' meaning trailing backslashes]
> 
> No, 'they' are still definitely in Python, but can usually be avoided.
> 
> As already mentioned, strings are automatically concatenated if they are 
> separated by only 
> whitespace (spaces/tabs/newlines).  But there is a difference between this 
> concatenation and 
> using a trailing backslash.  For example:
> 
> print('this, that, '
>  'the other')
>  
> gives -> 'this, that, the other'
> 
> print('this, that, \
>  the other')
> 
> gives -> 'this, that, the other'
> 
> The leading whitespace in the second example is significant, but is ignored 
> in the first.
> 
> The other places you can avoid the trailing backslash is within brackets, ie. 
> (), [] or {}.
> Here you can split at any 'natural' position, that is following a comma, dot 
> or an operator.
> 
> ['spam',
>  'eggs',
> 'bacon']
>  
> gives -> ['spam', 'eggs', 'bacon']
> 
> - 
> [2 +
>   3, 
>'spam']
>
> gives -> [5, 'spam']
> 
> -
> print('this' and
>  'that' or
>  'other')
> 
> gives -> 'that'
> 
> -
> print('{}'.
>  format('spam'))
> 
> gives -> 'spam'
> 
> These examples are somewhat contrived, but they do show what I'm talking 
> about.
> 
> Of course, you can still use the trailing backslash method, but when you can 
> avoid it it usually 
> looks cleaner.  Besides simply using either method to split long lines, it is 
> often used to line 
> things up, either for the appearance or for documentation.  Here is a 
> dictionary example of what 
> I mean (and the backslash method will NOT work here):
> 
> d = {1 : 'one',#  Describe this key/value pair
>  2 : 'two',#  Describe this one
>  3 : 'three'   #  Etc.
> }
> 
> Play around in the interactive mode to check out how this splitting works.

Thank you, Larry.  Your concise examples are nicely illustrative of the 
essentials.  I appreciate the explanation.

Thanks again to everyone.  

If I had the time, I would become a Python addict.
-- 
https://mail.python.org/mailman/listinfo/python-list