Re: [Tutor] New Line Problem

2018-02-02 Thread Alan Gauld via Tutor
On 02/02/18 02:44, Anna Lapre wrote:
> I am having a problem with creating a new line in a return statement for a
> function. It has a mix of a bunch of strings and variables. Everything that
> I want included will print, except for the new lines. I have tried "\n" but
> with no luck. Do you have any recommendations? Thanks.
> 
> http://py3.codeskulptor.org/#user301_SIdBE94Q8yi3qtM.py
> (it's the second function)

For a short function like this just post the code in the message, its
much easier to work with.

def singleline_diff_format(line1, line2, idx):
length_line1 = len(line1)
length_line2 = len(line2)
if (idx + 1) <= length_line1 and (idx + 1) <= length_line2:
equal = ""
code = (line1 +
equal[0:idx] + "^" +
line2)
return code
else:
return ""

You just need to add newline characters around the equal line.

code = (line1 +
'\n'+ equal[0:idx] + "^" + '\n' +
line2)

Or using a format string:

code = "%s\n%s\n%s" % (line1,equal[:idx]+'^',line2)

You also are not implementing the part of your specification
that says return an empty string if either input contains a
newline. testing the lengths does not work:

>>> s = "fred\njones"
>>> len(s)
10

You need to test whether '\n' is in the string.

By the way, your first function is much more complicated
than it needs to be, it is very inefficient and I'm pretty
sure its wrong too. Try:

singleline_diff("part trap", "part part")

And see if you get the right answer.

But you can make it a whole lot simpler if you just
compare the characters one by one and stop messing
around with indexes.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] New Line Problem

2018-02-02 Thread Peter Otten
Anna Lapre wrote:

> I am having a problem with creating a new line in a return statement for a
> function. It has a mix of a bunch of strings and variables. Everything
> that I want included will print, except for the new lines. I have tried
> "\n" but with no luck. Do you have any recommendations? Thanks.
> 
> http://py3.codeskulptor.org/#user301_SIdBE94Q8yi3qtM.py
> (it's the second function)

"\n" is indeed what you need:

>>> equal = ""
>>> index = 2
>>> line1 = "helllo"
>>> line2 = "heillo"
>>> print(line1 + "\n" + equal[:index] + "^\n" + line2)
helllo
==^
heillo

Note that you can repeat a string with

>>> "=" * 3
'==='
>>> "ab" * 2
'abab'

which combined with str.format allows the following alternative solutions:

>>> print("{}\n{}^\n{}".format(line1, "=" * index, line2))
helllo
==^
heillo

# requires Python 3.6
>>> print(f"{line1}\n{'='*index}^\n{line2}")
helllo
==^
heillo


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


[Tutor] New Line Problem

2018-02-02 Thread Anna Lapre
I am having a problem with creating a new line in a return statement for a
function. It has a mix of a bunch of strings and variables. Everything that
I want included will print, except for the new lines. I have tried "\n" but
with no luck. Do you have any recommendations? Thanks.

http://py3.codeskulptor.org/#user301_SIdBE94Q8yi3qtM.py
(it's the second function)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cmd line not correctly interpreted

2016-06-04 Thread Peter Otten
Alan Outhier wrote:

> I'm working on a Python script to call "sox" to convert ;ogg files to
> .mp3s.
> 
> In the following segment...:

To avoid garbled code as seen below please ensure that you post plain text. 
Thank you. 
> 
> *1outname=fname+".mp3"2fname=ReSpace(fname)   # substitute " "
> with
> "\ "3outname=ReSpace(outname)4cmdline="sox " + fname + " "
> +outname5print cmdline6rtncode=os.system(cmdline)7if rtncode
> <>
> 0:8print "Bad return code (" + str(rtncode) + ") from sox
> command"9sys.exit()*
> 
> ...I DO get the error trap (every time). Line 5 causes the following (for
> example) to be printed:
> 
> 
> *sox Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\
> the\ Blues Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\
> for\ the\ Blues.mp3*
> *Bad return code (512) from sox command *
> 
> I can however cop-past that output to bash and it works fine.
> 
> I get similar (but *as expected* more complicated problems if I comment
> out lines 2 & 3.
> 
> Please help! I'll send the whole program if requested.

The best approach is to use the subprocess module and let Python do the work 
for you. For example

import subprocess

fname = ... # may contain spaces
outname = fname + ".mp3"
# Pass arguments as a list, no need to use a shell:
subprocess.check_output(["sox", fname, outname])

If the sox invocation fails check_output will raise a CalledProcessError 
exception that you can examine for details, print or just let bubble up.

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


Re: [Tutor] Cmd line not correctly interpreted

2016-06-04 Thread Steven D'Aprano
On Fri, Jun 03, 2016 at 06:01:48PM -0700, Alan Outhier wrote:
> I'm working on a Python script to call "sox" to convert ;ogg files to .mp3s.
> 
> In the following segment...:
> 
> *1outname=fname+".mp3"2fname=ReSpace(fname)   # substitute " " with
> "\ "3outname=ReSpace(outname)4cmdline="sox " + fname + " "
> +outname5print cmdline6rtncode=os.system(cmdline)7if rtncode <>
> 0:8print "Bad return code (" + str(rtncode) + ") from sox
> command"9sys.exit()*

Your code is a mess. Try sending plain text instead of "rich text". When 
you send rich text, your mail client will mangle the line breaks and put 
them where ever it sees fit.

Also, there's no need for line numbers. Especially not when there are 
only nine lines.


> ...I DO get the error trap (every time). Line 5 causes the following (for
> example) to be printed:
> 
> 
> *sox Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\ the\
> Blues Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\
> the\ Blues.mp3*
> *Bad return code (512) from sox command *

According to the sox man page, it will only return 0, 1 or 2, not 512:

Exit status is 0 for no error, 1 if there is a problem with 
the command-line parameters, or 2 if an error occurs during
file processing.

http://sox.sourceforge.net/sox.html#DIAGNOSTICS

but I think that is a lie, as I can reproduce your error, without even 
using spaces:

py> os.system("sox ab cd")
sox: Can't open input file 'ab': No such file or directory
512

I'm surprised that you don't see the error message printed by sox. Are 
you redirecting stderr to a file or something? If so, please check the 
file.

You are using a relative path starting with "Carnegie\ Hall...". You 
probably should use an absolute path.



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


Re: [Tutor] Cmd line not correctly interpreted

2016-06-04 Thread Alan Gauld via Tutor
On 04/06/16 02:01, Alan Outhier wrote:
> I'm working on a Python script to call "sox" to convert ;ogg files to .mp3s.

1outname=fname+".mp3"
2fname=ReSpace(fname)   # substitute " " with "\ "
3outname=ReSpace(outname)
4cmdline="sox " + fname + " " +outname
5print cmdline
6rtncode=os.system(cmdline)
7if rtncode <> 0:
8print "Bad return code (" + str(rtncode) + ") from sox command"
9sys.exit()*

> ...I DO get the error trap (every time). Line 5 causes the following (for
> example) to be printed:
> 
> *sox Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\ the\
> Blues Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\
> the\ Blues.mp3*
> *Bad return code (512) from sox command *

> I can however cop-past that output to bash and it works fine.

It might be easier to use the subprocess call() function
and pass the filenames in that way. Also you could try upping the
verbosity of sox so it tells you more about the error.

I'd be suspicious of the filename format and try using
hard coded strings in raw format first:

outname = r"Carnegie Hall Jazz Band/Carnegie Hall Jazz Band/Frame for
 the Blues.mp3"

If that works it suggests your formatting function is not doing
what it should.

Another thing to try is to eliminate the complex filenames entirely
by copying the file to foo.ogg in the local directory. See if that
works. Then try a name with spaces in the current directory. Then a
directory name without spaces. etc etc.

By a process of elimination you can find out where things start
to fall over.

> Please help! I'll send the whole program if requested.

The ReSpace() function might be helpful.

But please send using plain text. Trying to reconstruct Python
code as I did above is extremely error prone.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Cmd line not correctly interpreted

2016-06-04 Thread Alan Outhier
I'm working on a Python script to call "sox" to convert ;ogg files to .mp3s.

In the following segment...:










*1outname=fname+".mp3"2fname=ReSpace(fname)   # substitute " " with
"\ "3outname=ReSpace(outname)4cmdline="sox " + fname + " "
+outname5print cmdline6rtncode=os.system(cmdline)7if rtncode <>
0:8print "Bad return code (" + str(rtncode) + ") from sox
command"9sys.exit()*

...I DO get the error trap (every time). Line 5 causes the following (for
example) to be printed:


*sox Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\ the\
Blues Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\
the\ Blues.mp3*
*Bad return code (512) from sox command *

I can however cop-past that output to bash and it works fine.

I get similar (but *as expected* more complicated problems if I comment out
lines 2 & 3.

Please help! I'll send the whole program if requested.

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


Re: [Tutor] Finding line number by offset value.

2016-02-22 Thread Peter Otten
Steven D'Aprano wrote:

> On Mon, Feb 22, 2016 at 01:41:42AM +, Alan Gauld wrote:
>> On 21/02/16 19:32, Cody West wrote:
> 
>> > I'm trying to take 48L, which I believe is the character number, and
>> > get the line number from that.

The documentation isn't explicit, but

"""
with open('/foo/bar/my_file', 'rb') as f:
  matches = rules.match(data=f.read())
"""

suggests that the library operates on bytes, not characters.

>> I'm not totally clear what you mean but, if it is that 48L
>> is the character count from the start of the file and you
>> want to know the line number then you need to count the
>> number of \n characters between the first and 48th
>> characters.
>> 
>> But thats depending on your line-end system of course,
>> there may be two characters on each EOL...
> 
> Provided your version of Python is built with "universal newline
> support", and nearly every Python is, then if you open the file in text
> mode, all end-of-lines are automatically converted to \n on reading.

Be careful, *if* the numbers are byte offsets and you open the file in 
universal newlines mode or text mode your results will be unreliable.

> If the file is small enough to read all at once, you can do this:

> offset = 48
> text = the_file.read(offset)
> print text.count('\n')

It's the offset that matters, not the file size; the first 48 bytes of a 
terabyte file will easily fit into the memory of your Apple II ;)


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


Re: [Tutor] Finding line number by offset value.

2016-02-21 Thread Steven D'Aprano
On Mon, Feb 22, 2016 at 01:41:42AM +, Alan Gauld wrote:
> On 21/02/16 19:32, Cody West wrote:

> > I'm trying to take 48L, which I believe is the character number, and get
> > the line number from that.
> 
> I'm not totally clear what you mean but, if it is that 48L
> is the character count from the start of the file and you
> want to know the line number then you need to count the
> number of \n characters between the first and 48th
> characters.
> 
> But thats depending on your line-end system of course,
> there may be two characters on each EOL... 

Provided your version of Python is built with "universal newline 
support", and nearly every Python is, then if you open the file in text 
mode, all end-of-lines are automatically converted to \n on reading.

If the file is small enough to read all at once, you can do this:

offset = 48
text = the_file.read(offset)
print text.count('\n')


to print a line number starting from 0.

If the file is too big to read all at once, you can do this:

# untested
running_total = 0
line_num = -1
offset = 4800  # say
for line in the_file:
running_total += len(line)
line_num += 1
if running_total >= offset:
print line_num
break


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


Re: [Tutor] Finding line number by offset value.

2016-02-21 Thread Alan Gauld
On 21/02/16 19:32, Cody West wrote:
> I'm using yara-python for some file scanning and I'm trying to take the
> offset in the 'strings' field and turn it into a line number.

I know nothing about yara except that its some kind of
pattern matching engine. However...

> (48L, '$execution', 'eval(base64_decode')
> 
> I'm trying to take 48L, which I believe is the character number, and get
> the line number from that.

I'm not totally clear what you mean but, if it is that 48L
is the character count from the start of the file and you
want to know the line number then you need to count the
number of \n characters between the first and 48th
characters.

But thats depending on your line-end system of course,
there may be two characters on each EOL... It depends
on your OS/version and possibly the character encoding
too. And if it's a binary file, who knows, as there
won't really be any line endings. And, as I understand
it, yara is targeted at reading byte patterns from
binary files?

Are you sure you really need the line number?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Finding line number by offset value.

2016-02-21 Thread Cody West
Hi,

I'm using yara-python for some file scanning and I'm trying to take the
offset in the 'strings' field and turn it into a line number.

http://yara.readthedocs.org/en/latest/yarapython.html

Below is what I'm working with.

(48L, '$execution', 'eval(base64_decode')

I'm trying to take 48L, which I believe is the character number, and get
the line number from that.

I know how to count lines until I match a string, but this is a little
harder.

I've searched all over the tubes and I can't seem to find anything useful.
Help a beginner out?

Thanks for your time,
Cody W
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] new line to list of strings send by email

2016-01-08 Thread Emil Natan
Hello list,

I have a function which receives a string and sends it as a body of an
email.

It is a part of a program which does certain checks on network
infrastructure. When a check fails I append error message to a
error_collector list:


if self.check_axfr_refused(ip):
 error_collector.append('%s:%s AXFR test for %s FAILED' %
   (ns, ip, self.domainname))

At the  end I send the alert like this:

if len(error_collector) != 0:
email_body = str(error_collector)
email_alert(email_body)

The problem is the resulted email (expectedly) has the alert message as one
long string.

['pdns6.ultradns.co.uk.:204.74.115.1 AXFR test for amazon.com FAILED',
'pdns6.ultradns.co.uk.:2610:a1:1017::1 AXFR test for amazon.com FAILED',
'ns4.p31.dynect.net.:204.13.251.31 AXFR test for amazon.com FAILED',...]

I tried adding '\n' to end of each string error_collector collects, but
then these were simply added to the resulted email.

What I want to achieve is that each collected error is shown on a separate
line in the email. Any advice will be well appreciated.

Here is the email sending function if in interest:

def email_alert(message, recipient=DEFAULT_RECIPIENT, subject_prefix=''):
''' Send email alert. '''
# check if we are running in quiet mode
if QUIET.lower() == 'yes':
return
msg = MIMEText(message)
msg['From'] = SENDER
msg['To'] = recipient
msg['Subject'] = subject_prefix + SUBJECT

s = smtplib.SMTP(SMTP_SERVER)
s.send_message(msg)
s.quit()

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


Re: [Tutor] new line to list of strings send by email

2016-01-08 Thread Bob Gailer
On Jan 8, 2016 11:03 AM, "Emil Natan"  wrote:
>
> Hello list,
>
> I have a function which receives a string and sends it as a body of an
> email.
>
> It is a part of a program which does certain checks on network
> infrastructure. When a check fails I append error message to a
> error_collector list:
>
>
> if self.check_axfr_refused(ip):
>  error_collector.append('%s:%s AXFR test for %s FAILED' %
>(ns, ip, self.domainname))
>
> At the  end I send the alert like this:
>
> if len(error_collector) != 0:
> email_body = str(error_collector)
> email_alert(email_body)
Instead of str( str(error_collector) ) try '\n'.join(error_collector)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] command line list arguments

2015-11-07 Thread Peter Otten
Garry Willgoose wrote:

> I want to input a python list as a command line argument as for example
> 
> python weathering-sens.py -daughter ['p0-50-50','p0-0-0-100’]
> 
> but what I get from sys.argv is [p0-50-50,p0-0-0-100] without the string
> delimiters on the list elements. I’m probably missing something really
> simple because sys.argv returns strings and probably strips the string
> delimiters in that conversion … but is there any way that I can keep the
> string delimiters so that inside the code I can just go (if arg is
> ['p0-50-50','p0-0-0-100’])
> 
> a=eval(arg)
> 
> or is there no alternative to doing this
> 
> python weathering-sens.py -daughter 'p0-50-50’ 'p0-0-0-100’
> 
> and doing the legwork of interpreting all the arguments individually (I’ve
> seen an example of this on the web).

With argparse it's really not that much legwork:

$ cat weathering-sens.py 
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--daughter", nargs="+")
args = parser.parse_args()
print(args.daughter)

$ python weathering-sens.py -d foo bar
['foo', 'bar']

$ python weathering-sens.py --daughter p0-50-50 p0-0-0-100
['p0-50-50', 'p0-0-0-100']

Note that args.daughter is a list of strings -- no need for eval().

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


Re: [Tutor] command line list arguments

2015-11-07 Thread Chris Warrick
On 7 November 2015 at 02:56, Garry Willgoose
 wrote:
> I want to input a python list as a command line argument as for example
>
> python weathering-sens.py -daughter ['p0-50-50','p0-0-0-100’]
>
> but what I get from sys.argv is [p0-50-50,p0-0-0-100] without the string 
> delimiters on the list elements. I’m probably missing something really simple 
> because sys.argv returns strings and probably strips the string delimiters in 
> that conversion … but is there any way that I can keep the string delimiters 
> so that inside the code I can just go (if arg is ['p0-50-50','p0-0-0-100’])
>
> a=eval(arg)
>
> or is there no alternative to doing this
>
> python weathering-sens.py -daughter 'p0-50-50’ 'p0-0-0-100’
>
> and doing the legwork of interpreting all the arguments individually (I’ve 
> seen an example of this on the web).

1. NEVER use eval().
2. Trying to pass Python code as arguments looks bad.  Don’t do that.
3. Your issues with '' are caused by your shell. You would need to
wrap your entire thing in quotes first, or use escaping. But instead,
4. Use argparse or another argument parsing solution, and implement it
with two arguments.

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


[Tutor] command line list arguments

2015-11-07 Thread Garry Willgoose
I want to input a python list as a command line argument as for example

python weathering-sens.py -daughter ['p0-50-50','p0-0-0-100’]

but what I get from sys.argv is [p0-50-50,p0-0-0-100] without the string 
delimiters on the list elements. I’m probably missing something really simple 
because sys.argv returns strings and probably strips the string delimiters in 
that conversion … but is there any way that I can keep the string delimiters so 
that inside the code I can just go (if arg is ['p0-50-50','p0-0-0-100’])

a=eval(arg)

or is there no alternative to doing this

python weathering-sens.py -daughter 'p0-50-50’ 'p0-0-0-100’

and doing the legwork of interpreting all the arguments individually (I’ve seen 
an example of this on the web).





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


Re: [Tutor] Command Line Editting: How to improve options?

2015-04-03 Thread Rajbir Singh
pycharm is IDE for python, ive been using it for a while now, compiles
python script, works as a text editor, allows downloading third party libs,
so far i havnt found anything that i need as python coder and it doesnt
have!! give it a try -- PyCharm

On Fri, Apr 3, 2015 at 4:32 AM, J L jnl_pub...@yahoo.com.dmarc.invalid
wrote:

 Thank you Steve.


 This electronic mail including any attachments may contain information
 that is privileged, confidential, and/or otherwise protected from
 disclosure to anyone other than its intended recipient(s). Any
 dissemination of this electronic email or its contents including any
 attachments is prohibited without prior consent.



  On Thursday, April 2, 2015 5:09 AM, Steven D'Aprano 
 st...@pearwood.info wrote:


  On Thu, Apr 02, 2015 at 06:36:03AM +, J L wrote:
   Win 7Python v 3.4.3
  I'm new to Python and only have coursework under my belt in another
  object oriented programming language as well as limited systems
  skills. After launching Python from the command line with py.exe, it
  appears that the interrupter starts up fine. I've read on Python.Org's
  site in a tutorial section that some interrupters offer command line
  editing beyond simple use of the arrow keys and backspace. It does not
  appear that my environment is allowing these greater abilities. How
  does one afford increased abilities to edit commands within Python's
  interrupter? Thank you.


 Sadly, Windows does not offer much in the way of powerful interactive
 commands like most Linux shells do. You can try these options:

 - try using Python's IDLE:

 http://www.google.com.au/search?q=how+to+run+IDLE+python

 - Use a commercial third-party IDE (Integrated Development
 Environment) such as PyCharm, Anaconda or Komodo. Some of them may cost
 money, but they may have free or trial versions.

 - Or a third-party editor such as Spyder, if it comes with its own
 interactive shell.

 - I can strongly recomment iPython, which is very powerful and includes
 a lot of command-line features that even Linux shells don't:

 http://ipython.org/
 ‎
 If you've used Mathematica, you may love iPython's notepad feature.

 Now we start getting to slightly more complex options, which may not
 work, but it would be interesting to try:

 - Try installing pyreadline, and see it is will work with Python 3.4. If
 it does, you might be able to convince Python 3.4's rlcompleter module
 to work with it.

 - Still if pyreadline works with Python 3.4, you might like my command
 line tab completer and history module rather than the built-in one:

 http://code.google.com/p/tabhistory/source/browse/tabhistory.py

 I've never tested it on Windows, so I don't know if it will actually
 work or not.


 Good luck!



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



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

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


[Tutor] Command Line Editting: How to improve options?

2015-04-02 Thread J L
 Win 7Python v 3.4.3
I'm new to Python and only have coursework under my belt in another object 
oriented programming language as well as limited systems skills. 
After launching Python from the command line with py.exe, it appears that the 
interrupter starts up fine. I've read on Python.Org's site in a tutorial 
section that some interrupters offer command line editing beyond simple use of 
the arrow keys and backspace. It does not appear that my environment is 
allowing these greater abilities.
How does one afford increased abilities to edit commands within Python's 
interrupter?
Thank you.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Editting: How to improve options?

2015-04-02 Thread J L
Thank you Steve. 


This electronic mail including any attachments may contain information that is 
privileged, confidential, and/or otherwise protected from disclosure to anyone 
other than its intended recipient(s). Any dissemination of this electronic 
email or its contents including any attachments is prohibited without prior 
consent.
 


 On Thursday, April 2, 2015 5:09 AM, Steven D'Aprano st...@pearwood.info 
wrote:
   

 On Thu, Apr 02, 2015 at 06:36:03AM +, J L wrote:
  Win 7Python v 3.4.3
 I'm new to Python and only have coursework under my belt in another 
 object oriented programming language as well as limited systems 
 skills. After launching Python from the command line with py.exe, it 
 appears that the interrupter starts up fine. I've read on Python.Org's 
 site in a tutorial section that some interrupters offer command line 
 editing beyond simple use of the arrow keys and backspace. It does not 
 appear that my environment is allowing these greater abilities. How 
 does one afford increased abilities to edit commands within Python's 
 interrupter? Thank you. 


Sadly, Windows does not offer much in the way of powerful interactive 
commands like most Linux shells do. You can try these options:

- try using Python's IDLE:

http://www.google.com.au/search?q=how+to+run+IDLE+python

- Use a commercial third-party IDE (Integrated Development 
Environment) such as PyCharm, Anaconda or Komodo. Some of them may cost 
money, but they may have free or trial versions.

- Or a third-party editor such as Spyder, if it comes with its own 
interactive shell.

- I can strongly recomment iPython, which is very powerful and includes 
a lot of command-line features that even Linux shells don't:

http://ipython.org/
‎
If you've used Mathematica, you may love iPython's notepad feature.

Now we start getting to slightly more complex options, which may not 
work, but it would be interesting to try:

- Try installing pyreadline, and see it is will work with Python 3.4. If 
it does, you might be able to convince Python 3.4's rlcompleter module 
to work with it.

- Still if pyreadline works with Python 3.4, you might like my command 
line tab completer and history module rather than the built-in one:

http://code.google.com/p/tabhistory/source/browse/tabhistory.py

I've never tested it on Windows, so I don't know if it will actually 
work or not.


Good luck!



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


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


Re: [Tutor] Command Line Editting: How to improve options?

2015-04-02 Thread Steven D'Aprano
On Thu, Apr 02, 2015 at 06:36:03AM +, J L wrote:
  Win 7Python v 3.4.3
 I'm new to Python and only have coursework under my belt in another 
 object oriented programming language as well as limited systems 
 skills. After launching Python from the command line with py.exe, it 
 appears that the interrupter starts up fine. I've read on Python.Org's 
 site in a tutorial section that some interrupters offer command line 
 editing beyond simple use of the arrow keys and backspace. It does not 
 appear that my environment is allowing these greater abilities. How 
 does one afford increased abilities to edit commands within Python's 
 interrupter? Thank you. 


Sadly, Windows does not offer much in the way of powerful interactive 
commands like most Linux shells do. You can try these options:

- try using Python's IDLE:

http://www.google.com.au/search?q=how+to+run+IDLE+python

- Use a commercial third-party IDE (Integrated Development 
Environment) such as PyCharm, Anaconda or Komodo. Some of them may cost 
money, but they may have free or trial versions.

- Or a third-party editor such as Spyder, if it comes with its own 
interactive shell.

- I can strongly recomment iPython, which is very powerful and includes 
a lot of command-line features that even Linux shells don't:

http://ipython.org/
‎
If you've used Mathematica, you may love iPython's notepad feature.

Now we start getting to slightly more complex options, which may not 
work, but it would be interesting to try:

- Try installing pyreadline, and see it is will work with Python 3.4. If 
it does, you might be able to convince Python 3.4's rlcompleter module 
to work with it.

- Still if pyreadline works with Python 3.4, you might like my command 
line tab completer and history module rather than the built-in one:

http://code.google.com/p/tabhistory/source/browse/tabhistory.py

I've never tested it on Windows, so I don't know if it will actually 
work or not.


Good luck!



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


Re: [Tutor] Single line webserver [was: Tutor Digest, Vol 93, Issue 38]

2011-11-08 Thread Steven D'Aprano

Rich Lovely wrote:


I'd like to draw your attention to my original message: a google
search is similarly lacking in relevant results.  Shouldn't it be
clear from how easy it is to find SimpleHttp that it clearly /isn't/
what I'm looking for? Perhaps I should have mentioned that, but I
thought I'd made it clear I'd tried a websearch.


Yes, you should have mentioned that SimpleHttp was not the one-liner you 
were looking for. That would have been useful to know :)


Your request was for a one-liner web server, and you claimed to have 
done a search which came up with nothing relevant. Since a simple search 
did in fact come up with an apparently relevant one-liner, the most 
obvious conclusions were that your search skills are very lousy, or that 
you were mistaken (i.e. lying) about having attempted to search first. 
Coming from an apparent first-time poster with no reputation I was aware 
of, neither would have surprised me. I'm glad that neither is actually 
the case.




The code I remember was a Socket-based webserver, written in one -
albeit rather long - line.


That would have been useful information to have mentioned at the time.

For what little it's worth, here's a 15 line socket-based web server:


import socket
template = ('HTTP/1.0 200 OK\n\nhtmlheadtitleWelcome %s!/title'
  '/headbodyh1Header.../h1...and body.brYour request was: '
  '%s/body/html')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 8080))
sock.listen(1)
print Listening on port 8080
while True:
client, address = sock.accept()
cfile = client.makefile('rw', 0)
cfile.write(template % (str(address), cfile.readline().strip()))
cfile.close()
client.close()


Save this as web.py, run python web.py, and then in your browser go 
to http://localhost:8080


Turning this into a one-liner is left as an exercise. This may be useful:

http://pauldotcom.com/2011/10/python-one-line-shell-code.html



P.S. I note you're replying to the digest. Thank you for trimming your 
reply, rather than including the entire digest, but please note the 
request at the top of each digest:


When replying, please edit your Subject line so it is
more specific than Re: Contents of Tutor digest...



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


Re: [Tutor] Single line webserver

2011-11-08 Thread Prasad, Ramit
Windows Command Prompt gotta be the most powerful language on earth, it 
has a full-blown server in a single word:

C:\Program Files\Apache Software Foundation\Apache2.2\bin httpd.exe

/sarcasm

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Single line webserver

2011-11-07 Thread Rich Lovely
Hi all, I was part of this list a couple of years ago, and a recent discussion 
at a python dojo brought to mind something I'd seen then:  a one-liner 
(potentially single statement) webserver.  I'm pretty sure it was posted to 
this list, but I can't find it in the archives, and a google search is 
similarly lacking in relevant results.

I was wondering if anyone (maybe the original author?) had a copy they could 
send me.

Rich RoadieRich Lovely

There are 10 types of people in the world:
Those who know binary,
Those who do not,
And those who are off by one.

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


Re: [Tutor] Single line webserver

2011-11-07 Thread Steven D'Aprano

Rich Lovely wrote:

Hi all, I was part of this list a couple of years ago, and a recent discussion 
at a python dojo brought to mind something I'd seen then:  a one-liner 
(potentially single statement) webserver.  I'm pretty sure it was posted to 
this list, but I can't find it in the archives, and a google search is 
similarly lacking in relevant results.

I was wondering if anyone (maybe the original author?) had a copy they could 
send me.


https://duckduckgo.com/html/?q=python%20one%2Dliner%20web%20server

Hits #2 #3 and #4 are:

http://tobyho.com/2010/04/26/one-liner-webserver-with/
http://www.garyrobinson.net/2004/03/one_line_python.html
http://aroberge.blogspot.com/2010/08/my-favourite-python-one-liner.html



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


Re: [Tutor] Single line webserver

2011-11-07 Thread Alan Gauld

On 07/11/11 23:23, Rich Lovely wrote:


a one-liner (potentially single statement) webserver.


There is a python module in the standard library that implements a basic 
webserver, presumably it was based on that.


Try the docs for the library modules...

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Single line webserver

2011-11-07 Thread Lie Ryan

On 11/08/2011 10:23 AM, Rich Lovely wrote:

Hi all, I was part of this list a couple of years ago, and a recent discussion 
at a python dojo brought to mind something I'd seen then:  a one-liner 
(potentially single statement) webserver.  I'm pretty sure it was posted to 
this list, but I can't find it in the archives, and a google search is 
similarly lacking in relevant results.

I was wondering if anyone (maybe the original author?) had a copy they could 
send me.



Windows Command Prompt gotta be the most powerful language on earth, it 
has a full-blown server in a single word:


C:\Program Files\Apache Software Foundation\Apache2.2\bin httpd.exe

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


Re: [Tutor] Command line scripts

2011-01-13 Thread David Hutto
As you can tell, I was excited, and impressed by my own work, and
therefore thought you should follow my wise and almighty work.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line scripts

2011-01-13 Thread David Hutto
On Thu, Jan 13, 2011 at 8:41 AM, David Hutto smokefl...@gmail.com wrote:
 As you can tell, I was excited, and impressed by my own work, and
 therefore thought you should follow my wise and almighty work.


On the flip side, it's like being an electrician, and seeing the
lights come on when you hook the box up.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line scripts

2011-01-12 Thread David Hutto
On Sun, Jan 9, 2011 at 9:03 AM, ALAN GAULD alan.ga...@btinternet.com wrote:


 The following line is what I mean by calling a  command line from within the
app
 using subprocess.

 self.espeak =  subprocess.Popen(['espeak', word],stdout  =
 subprocess.PIPE).communicate()[0]

 OK, Now I understand.
 You want to call an external application from within your code
 via subprocess. And you want to know if that will work ok in a
 wxPython application?

  In other words,  is a command line app different from
  bindings in a compiled  app?

 When you call an app using subprocess it spawns an entirely
 separate process in the OS. There is no linkage to your process
 apart from the redirection of stdin/stdout/stderr back to your
 app instead of to a console.

  So-called exe generators simply bundle the interpreter  witrh
  the code and auto run it.

 So it's basically just installing  a sandbox version of python?

 Sort of, its a minimalist version of python with only the modules
 needed to run the app. And you can't run the interpreter on its
 own you can only run the packaged app.

 Which ultimately is, if I have a standalone  application, that doesn't
 come from a command line terminal launching(which I  haven't gotten to
 yet), is using the command line calls going through  subprocess going
 to be called without the terminal, or will it open a  terminal
 automatically to make those calls?

 The app (eSpeak in your example) will see your app as its console.
 That is, it will send all output to your app and read all input from your
 app

I was thinking that since the app is called from the command line with
python(which is no different, than using any other command line
script-just like espeak 'word' - python script.py), it would be go
back to the shell window it was spawned/called from through python and
utilize the command line there. Similar to how when I run the app, my
data can be through the app text/label fields, or, through the
terminal window itself.

 (so you need to make sure it gets any input it is expecting!)
 The other thing to watch in a wxPython (or any other GUI framework)
 is that if the app runs for a long time your app may freeze from
 the user's perspective, so you may want to run it in the background
 or as a separate thread in your app.

 Or will all of my python  apps need to have a command line terminal
 open to launch them.

 No, your app takes over the job of the terminal. When you launch
 a program from the terninal the terminal app(for it is just an app like
 any other) is doing the same as you, it is spawning a subprocess
 that sends its output back to the teminal for it to display.

 In fact you might find it a useful exercise to build a very basic terminal
 app in wxPython first. Read commands from a command input field
 and display the output in a text widget... Execute the commands
 via subprocess. Its a good way to get used to using subprocess
 and experimenting with its various options. If you are very keen
 you can start adding command history and search etc to it too...


I'll eventually get to the above(I have a lot of projects, some will
involve command line/subprocess:), but thanks for the explanation. I'm
guessing that something like cxfreezeI haven't looked it over
thoroughly) might be what I was looking for. Although in the end, it's
just for other to see your work, because most of my own apps are for
me personally, which might be a good thing.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line scripts

2011-01-12 Thread David Abbott
On Wed, Jan 12, 2011 at 9:29 PM, David Hutto smokefl...@gmail.com wrote:
 On Sun, Jan 9, 2011 at 9:03 AM, ALAN GAULD alan.ga...@btinternet.com wrote:


 The following line is what I mean by calling a  command line from within the
app
 using subprocess.

 self.espeak =  subprocess.Popen(['espeak', word],stdout  =
 subprocess.PIPE).communicate()[0]


I came up with this as an example, I am still learning also :)

[code]
#!/usr/bin/python

# wx python + espeak

from subprocess import call
import sys
import wx

class ESpeak(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(360, 370))

panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)

st1 = wx.StaticText(panel, -1, 'Enter Saying: ')

self.tc1 = wx.TextCtrl(panel, -1, size=(180, -1))

button_send = wx.Button(panel, 1, 'Say')

hbox1.Add(st1, 0, wx.LEFT, 10)
hbox1.Add(self.tc1, 0, wx.LEFT, 10)

vbox.Add(hbox1, 0, wx.TOP, 50)
vbox.Add(button_send, 0, wx.ALIGN_CENTER | wx.TOP | wx.TOP |
wx.BOTTOM, 100)

self.Bind(wx.EVT_BUTTON, self.OnSpeak, id=1)
panel.SetSizer(vbox)

self.Centre()
self.ShowModal()
self.Destroy()

def OnSpeak(self, event):
say = self.tc1.GetValue()
if say != :
espeak = /usr/bin/espeak
call([espeak, say])
else:
dlg = wx.MessageDialog(self, 'What did you say?', 'Error',
wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()

app = wx.App()
ESpeak(None, -1, 'wxESpeak')
app.MainLoop()
[/code]

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


Re: [Tutor] Command line scripts

2011-01-12 Thread David Hutto
I think it works great as an easy integration for the blind(although
I'm sure there is already a python module for that somewhere), as long
as they have espeak(or it can be easily adapted), but also if you just
like the ai feel of a voice in your apps.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line scripts

2011-01-12 Thread David Hutto
Although, I'd just go with a function that gets passed the text, that
way it was reusable, like the one I gave.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line scripts

2011-01-12 Thread David Hutto
Although, you did just that, didn't pay attention to the whole thing.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line scripts

2011-01-09 Thread ALAN GAULD


 The following line is what I mean by calling a  command line from within the 
app
 using subprocess.
 
 self.espeak =  subprocess.Popen(['espeak', word],stdout  =
 subprocess.PIPE).communicate()[0]

OK, Now I understand. 
You want to call an external application from within your code 
via subprocess. And you want to know if that will work ok in a 
wxPython application?

  In other words,  is a command line app different from
  bindings in a compiled  app?

When you call an app using subprocess it spawns an entirely 
separate process in the OS. There is no linkage to your process 
apart from the redirection of stdin/stdout/stderr back to your 
app instead of to a console.

  So-called exe generators simply bundle the interpreter  witrh
  the code and auto run it.
 
 So it's basically just installing  a sandbox version of python?

Sort of, its a minimalist version of python with only the modules 
needed to run the app. And you can't run the interpreter on its 
own you can only run the packaged app.

 Which ultimately is, if I have a standalone  application, that doesn't
 come from a command line terminal launching(which I  haven't gotten to
 yet), is using the command line calls going through  subprocess going
 to be called without the terminal, or will it open a  terminal
 automatically to make those calls?

The app (eSpeak in your example) will see your app as its console. 
That is, it will send all output to your app and read all input from your 
app (so you need to make sure it gets any input it is expecting!)
The other thing to watch in a wxPython (or any other GUI framework) 
is that if the app runs for a long time your app may freeze from 
the user's perspective, so you may want to run it in the background 
or as a separate thread in your app.

 Or will all of my python  apps need to have a command line terminal
 open to launch them. 

No, your app takes over the job of the terminal. When you launch 
a program from the terninal the terminal app(for it is just an app like 
any other) is doing the same as you, it is spawning a subprocess 
that sends its output back to the teminal for it to display.

In fact you might find it a useful exercise to build a very basic terminal 
app in wxPython first. Read commands from a command input field 
and display the output in a text widget... Execute the commands 
via subprocess. Its a good way to get used to using subprocess 
and experimenting with its various options. If you are very keen 
you can start adding command history and search etc to it too...

HTH,

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


Re: [Tutor] Command line scripts

2011-01-08 Thread Alan Gauld

David Hutto smokefl...@gmail.com wrote


If I use as command line script, is there any disruption in the
execution of the code using wxpython.


I don't understand the question.
wxPython is a GUI toolkit so how would you have a command
line script using wxPython? Or do you mean running a wxPython
GUI program from the command line? - that should work just fine.


In other words, is a command line app different from
bindings in a compiled app?


What kind of bindings?
And what do you mean by a compiled app?
Python is interpreted (or actually compiled to byte code
and the byte code is interpreted - but its the same principle).
So-called exe generators simply bundle the interpreter witrh
the code and auto run it.

And wxPython is irrelevant to that debate since it is just
a set of modules regardless of how you run it.


  @ trace
  def play(self, event = None, text = None):
  if event == None:
  self.textlist = []
  for item in text.split(' '):
  self.textlist.append(item)
  print self.textlist
  for word in self.textlist:
  self.espeak =
  subprocess.Popen(['espeak', 
word], stdout =


subprocess.PIPE).communicate()[0]
  if event != None:
  self.textlist = []
  for item in 
self.text2speech.GetValue().split(' '):

  self.textlist.append(item)
  print self.textlist
  for word in self.textlist:
  self.espeak =
   subprocess.Popen(['espeak', 
word], stdout =


subprocess.PIPE).communicate()[0]


Sorry, I'm missing the significance of this function?

Confused,.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


[Tutor] Adding line numbers to a Python Script

2010-06-12 Thread Sudip Bhattacharya
I quote this example (and the problem that I am facing trying to understand)
from the book Beginning Python - From Novice to Professional by Magnus Lie
Hetland

Page 227

# numberlines.py
import fileinput(1)

for line in fileinput.input(inplace = true)(2)
   line = line.rstrip()(3)
   num=fileinput.lineno()..(4)
   print '%-40s #%2i' %(line,num).(5)


Question: Please help me understand:

Line (3) - Are we stripping the entire line of code first, inserting the
code at the end (line (5)) and then placing it back at the same place ?

Line (5) - What does the individual characters in the expression Print
'%-40s #%2i' %(line,num) mean ?

 - '-40s' : is this the space [what does -40s mean] that we are
creating post - which the line nos is inserted #%2i ?
 - What does '%2 mean ? - Is that 2 cursor spaces of width ?

Much thanks in advance...
-- 
Thanks and regards,
Sudip Bhattacharya

Mobile: +91  100 706
Home Land line: +91 11 22237561
Office Land line: +91 0124 4321078
eMail ID: sud...@sudipb.com; sud...@gmail.com

Please visit my website at: www.sudipb.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding line numbers to a Python Script

2010-06-12 Thread Alan Gauld


Sudip Bhattacharya sud...@sudipb.com wrote


for line in fileinput.input(inplace = true)(2)
  line = line.rstrip()(3)
  num=fileinput.lineno()..(4)
  print '%-40s #%2i' %(line,num).(5)

Line (3) - Are we stripping the entire line of code first, inserting 
the
code at the end (line (5)) and then placing it back at the same 
place ?


Fire up the python interpreter and type:


help(.strip)


See if you understand what it says. If not come back here and ask 
again.
Python's help fuinction is very powerful, learn to use it for fast 
answers.


Line (5) - What does the individual characters in the expression 
Print

'%-40s #%2i' %(line,num) mean ?


These are formatting characters. If you read the Simple Sequences
topic in my tutor you will get some easier examples to try.

Then read the Python documentation - search for format string...


- '-40s' : is this the space [what does -40s mean] that we are
creating post - which the line nos is inserted #%2i ?


Again fitre up the Python interpreter and try it out.


%-40s % Some string here


Now try again with a different number, Try missing out the minus sign.
Can you see what the different bits do?

Now go read the documentation again. Try some different data types.
Experiment. Its the best way to really understand.


- What does '%2 mean ? - Is that 2 cursor spaces of width ?


Close but again Read the docs, try it, experiment. See for yourself.


%2i %  7


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] bind line-oriented device output?

2010-03-29 Thread Tom Roche

http://mail.python.org/pipermail/tutor/2010-March/075438.html
 I'd like to learn to pythonically redirect the output from a
 line-oriented character device to a particular file or process,
 regardless of focus, on a generic graphical OS. But I don't want to
 redirect stdin entirely.
...
 It Would Be Nice, and useful for this seminar's mechanics, to be
 able to run some code to which one could say, see this device? and
 this file? Make the device's output go only to that file. For extra
 credit, don't let anything else write that file while this code is
 running.

http://mail.python.org/pipermail/tutor/2010-March/075443.html
 if you can assure that the target computer will be running a certain
 set of python features (i.e. Tkinter/pyGTK+/wxPython, etc)

Presuming they're available on the user's platform and not too onerous
to install, I can definitely say, if you want goodness/, you need
to install necessaries/.

 you can fairly easily write a program that will run fullscreen and
 continually grab focus to whatever widget (in this case a text entry
 field) you want.

*Continually* grabbing focus to a UI is functionally (from the user's
point of view) equivalent to redirecting stdin, no? The user is made
unable to do anything but take attendance for the duration of the
task. In fact, for this usecase, continually grabbing focus is worse,
since the user would be unable to, e.g., read the directions for
setting up the audio. To clarify the usecase:

The barcode scanner (here, a Wasp WLS9500) is connected to an ordinary
multiprocessing laptop (which may be linux, mac, or windows) on which
the user will want to do other things while taking attendance: the
attendees don't come in all at once, and the user must accomplish
other tasks while taking attendance (notably setting up to record the
seminar audio). Hence the desired application

0 is portable.

1 does not redirect all of stdin, only the output from the scanner.
  The user is allowed to continue to work on other tasks (e.g. with
  output from the laptop's keyboard going to whatever frame), with
  only the output from the scanner being bound to a particular file or
  process.

2 does not continually grab focus. The user is allowed to continue to
  work on other tasks (e.g. with output from the laptop's keyboard
  going to whatever frame), with only scanner events being bound to a
  particular frame or widget.

But what might satisfy the usecase is

 if the device is something like the CueCat and reports a control
 character (I think it's alt+f7 for the cuecat), then at least on
 linux/windows I think it's much more trivial. You just have to
 register a global hotkey handler that will send the focus to that
 particular window.

I'll read the Product Reference Guide and hope it tells me that the
Wasp WLS9500 reports a control character. Unfortunately when I
search the PDF

http://tinyurl.com/waspWLS9500manual

for control character I get no hits. Are there synonyms for that
term in this context?

TIA, Tom Roche tom_ro...@pobox.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bind line-oriented device output?

2010-03-29 Thread Wayne Werner
On Mon, Mar 29, 2010 at 10:56 AM, Tom Roche tom_ro...@pobox.com wrote:

 I'll read the Product Reference Guide and hope it tells me that the
 Wasp WLS9500 reports a control character. Unfortunately when I
 search the PDF

 http://tinyurl.com/waspWLS9500manual

 for control character I get no hits. Are there synonyms for that
 term in this context?


Take a look at the bottom of 8-5, it has some prefix/suffix values.
Apparently you can set it to send prefixdata and it looks like by
perusing the manual and probably a bit of trial and error you can set it up
to send one of any number of CTRL characters as the prefix. I don't know of
any windows program that uses ctrl-] as a hotkey though I'm sure there are
some.

For Python registering hotkeys, a quick google search pulled up these:
http://www.islascruz.org/html/index.php/blog/show/HotKeysonWindows.html
http://bytes.com/topic/python/answers/574341-how-create-global-hotkey (mainly
lots of links to other sites)

I wasn't able to find anything super definitive on mac, though, which is too
bad.

Anyhow, HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bind line-oriented device output?

2010-03-29 Thread Fiyawerx
On Mon, Mar 29, 2010 at 11:56 AM, Tom Roche tom_ro...@pobox.com wrote:


 http://mail.python.org/pipermail/tutor/2010-March/075438.html
  I'd like to learn to pythonically redirect the output from a
  line-oriented character device to a particular file or process,
  regardless of focus, on a generic graphical OS. But I don't want to
  redirect stdin entirely.
 ...
  It Would Be Nice, and useful for this seminar's mechanics, to be
  able to run some code to which one could say, see this device? and
  this file? Make the device's output go only to that file. For extra
  credit, don't let anything else write that file while this code is
  running.



 1 does not redirect all of stdin, only the output from the scanner.
  The user is allowed to continue to work on other tasks (e.g. with
  output from the laptop's keyboard going to whatever frame), with
  only the output from the scanner being bound to a particular file or
  process.


This may be out of my league, but what about pyUSB? (
http://pyusb.sourceforge.net/docs/1.0/tutorial.html)

Possibly a program that just runs in the background, waits for input from
the usb scanner, and appends the id to a specified file when it catches it?
That way you also don't need to keep the file open the whole time, in case
someone accidentally forgets to plug it in or shuts down while the program
is still writing? I'm sure there are a lot of better ways to handle the
actual file writing, but thought it might help.

Just a noobs $.02
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] bind line-oriented device output?

2010-03-28 Thread Tom Roche

I'd like to learn to pythonically redirect the output from a
line-oriented character device to a particular file or process,
regardless of focus, on a generic graphical OS. But I don't want to
redirect stdin entirely. Here's the usecase:

My school has a seminar for which we record attendance by scanning the
student ID card, or rather the barcode on its back, with a handheld
USB scanner. This is pretty straightforward, except that the barcode
scanner is like a keyboard writing the ASCII equivalent of the barcode
(== the student's ID#) to stdin. FWIW, the scanner writes lines: I'm
not sure if EOL is \r, \n, or \r\n, but I suspect the latter.

Since the scanner is connected to an ordinary multiprocessing laptop on
which one will likely be doing other things while scanning (notably
setting up to record the presenter), it sometimes happens (especially
until one learns to pay attention to this) that one writes to a frame
other than the text file into which we want record attendee ID#s. This
semester recurs every {fall, spring}, so someone faces this {pitfall,
learning curve} at regular intervals.

How to prevent writing the wrong target? One trivial solution--shlep a
dedicated USB host for the scanner--is deprecated. An OS-specific
solution (e.g. relying on a linux raw device) is also undesirable: I
use ubuntu, but others will probably use mac or windows.

Rather, It Would Be Nice, and useful for this seminar's mechanics, to
be able to run some code to which one could say, see this device? and
this file? Make the device's output go only to that file. For extra
credit, don't let anything else write that file while this code is
running.

Can python do that? Or does one need to get closer to the metal?

TIA, Tom Roche tom_ro...@pobox.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] command line invocation

2010-01-17 Thread Robert
Say that I have module spam.py  in  /tmp which is in PYTHONPATH.

in shell, my current directory is /tmp,
are line#3 and #4 --- http://paste.pocoo.org/show/166268/ -
equivalent --- i.e. yielding the same result ?

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


Re: [Tutor] command line invocation

2010-01-17 Thread Alan Gauld


Robert webtour...@gmail.com wrote 


in shell, my current directory is /tmp,
are line#3 and #4 --- http://paste.pocoo.org/show/166268/ -
equivalent --- i.e. yielding the same result ?


No need to use pastebin when its only 2 lines!

Since -m runs a module as a script I think the answer is yes. 

Where they would be different is if you were not in the same folder 
as the module. Then the -m option would search the PYTHONPATH 
whereas without -m I think it would not search for the module, you 
would need to specify the location.


I think...

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] First line of a python program

2009-10-12 Thread Katt

Hello all,

Numerous times I see the following as the first line of a python program:

#! /usr/bin/python

What is this for or do for the program?

Thanks in advance,

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


Re: [Tutor] First line of a python program

2009-10-12 Thread Mark K. Zanfardino
From http://en.wikipedia.org/wiki/Shebang_(Unix): 

In computing, a shebang (also called a hashbang, hashpling, pound bang,
or crunchbang) refers to the characters #! when they are the first two
characters in a text file. In a Unix-like operating system, the program
loader takes the presence of these two characters as an indication that
the file is a script, and tries to execute that script using the
interpreter specified by the rest of the first line in the file.

Mark

On Mon, 2009-10-12 at 14:49 -0700, Katt wrote:
 Hello all,
 
 Numerous times I see the following as the first line of a python program:
 
 #! /usr/bin/python
 
 What is this for or do for the program?
 
 Thanks in advance,
 
 Katt
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] First line of a python program

2009-10-12 Thread Steve Willoughby
On Mon, Oct 12, 2009 at 02:49:34PM -0700, Katt wrote:
 Hello all,
 
 Numerous times I see the following as the first line of a python program:
 
 #! /usr/bin/python

As far as Python is concerned, it is a comment.
Anything from the # character to the end of the line is a comment.

If you want to execute this script, you need to run the Python
interpreter and tell it to load the script file and run it
for you:

  $ /usr/bin/python myscript

You could just set your script to be executable (by setting the
right permission bits) and then you can run it as a command
without naming python yourself:

  $ myscript

(that assumes it's in a directory in your PATH, of course,
or you'd have to type the path to the script as well.)

That allows you to write scripts which act like any other 
command on your system.

In order to do that, though, the system needs to know what interpreter
to use to actually run your script.  Unix uses the convention of looking
at the first few bytes of the program file.  If they start with #! then
the remainder of the first line is assumed to be the name of the interpreter
program, so with #!/usr/bin/python at the top of your file, Unix will
know to run it as /usr/bin/python myscript.

If you use an operating system other than Unix, or invoke the interpreter
yourself (typing python myscript), then this line is completely ignored.

HTH
HAND
 
 What is this for or do for the program?
 
 Thanks in advance,
 
 Katt
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First line of a python program

2009-10-12 Thread Markus Flatscher
The short answer is, it's a shebang: http://en.wikipedia.org/wiki/Shebang_(Unix)

Let us know if this clarifies anything.

M.

On Mon, 12 Oct 2009 14:49:34 -0700
 Katt the_only_kat...@verizon.net wrote:
Hello all,

Numerous times I see the following as the first line of a python program:

#! /usr/bin/python

What is this for or do for the program?

Thanks in advance,

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

--
Markus Flatscher, Project Editor
ROTUNDA, The University of Virginia Press
PO Box 801079, Charlottesville, VA 22904-4318 USA
Courier: 310 Old Ivy Way, Suite 302, Charlottesville VA 22903
Email: markus.flatsc...@virginia.edu
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] hello.py: line 1: print: command not found

2008-08-11 Thread steve
Hi

In order to execute python script by fedora terminal ; insert #! /bin/env 
python as the first line in the script.

Python scripts end with a file extension of .py, as 
indicated above.
It is also possible in Unix to automatically launch the Python 
interpreter without explicitly invoking it by name from the command line. If 
you 
are using any Unix-flavored system, you can use the shell-launching (sh-bang) 
first line of your program:
#!/usr/local/bin/pythonThis may futher help Source Core Python Programming

The file path, the part that follows the #!, is the full path 
location of the Python interpreter. As we mentioned before, it is usually 
installed in /usr/local/bin or /usr/bin. If not, be sure to 
get the exact pathname correct so that you can run your Python scripts. 
Pathnames that are not correct will result in the familiar Command not 
found error message.
As a preferred alternative, many Unix systems have a command 
named env, installed in either /bin or /usr/bin, 
which will look for the Python interpreter in your path. If you have 
env, your startup line can be changed to something like this:
#!/usr/bin/env python

or, if your env is located in /bin,
#!/bin/env python

env is useful when you either do not know exactly 
where the Python executable is located, or if it changes location often, yet 
still remains available via your directory path. Once you add the proper 
startup 
directive to the beginning of your script, it becomes directly executable, and 
when invoked, loads the Python interpreter first, then runs your script. As we 
mentioned before, Python no longer has to be invoked explicitly from the 
command. You only need the script name:
$ script.py




  ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Nested, line by line, file reading

2007-12-16 Thread jon vs. python
Hi everyone,
I have a file with this content:

1
1
1
1
1
1
1
2
1
1

I wanted a little script that would print the line containing 2 and every
line containing 1 after it. I've tried this:

 def p():
f = file(prueba.txt,'r')
for startline in f.read():
if startline.find(2) != -1:
print startline
for endline in f.read():
if endline.find(1) != -1:
print endline
break
f.close()


 p()
2

I found a way for doing it.

But still I don't really understand why I don't get two 1 lines printed.
It seems that every line is read in for startline f.read() so for endline
in f.read() will start reading but find no data, am I right?

Thanks, Jon.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread bob gailer
jon vs. python wrote:
 Hi everyone,
 I have a file with this content:

 1
 1
 1
 1
 1
 1
 1
 2
 1
 1

 I wanted a little script that would print the line containing 2 and 
 every line containing 1 after it. I've tried this:

  def p():
 f = file(prueba.txt,'r')
 for startline in f.read():
 if startline.find(2) != -1:
 print startline
 for endline in f.read():
 if endline.find(1) != -1:
 print endline
 break
 f.close()


  p()
 2

 I found a way for doing it.

 But still I don't really understand why I don't get two 1 lines 
 printed. It seems that every line is read in for startline f.read() 
 so for endline in f.read() will start reading but find no data, am I 
 right?
 From the manual: read([size]) Read at most size bytes from the file 
(less if the read hits EOF before obtaining size bytes). If the size 
argument is negative or omitted, read all data until EOF is reached.

Instead use readline().

Then realize that will also consume the entire file, so a nested 
readline() will return .

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread Luis N
On Dec 16, 2007 10:17 PM, jon vs. python [EMAIL PROTECTED] wrote:
 Hi everyone,
 I have a file with this content:

 1
 1
 1
 1
 1
 1
 1
 2
 1
 1

 I wanted a little script that would print the line containing 2 and every
 line containing 1 after it. I've tried this:

  def p():
 f = file(prueba.txt,'r')
 for startline in f.read():
 if startline.find(2) != -1:
 print startline
 for endline in f.read():
 if endline.find(1) != -1:
 print endline
 break
 f.close()


  p()
 2

 I found a way for doing it.

 But still I don't really understand why I don't get two 1 lines printed.
 It seems that every line is read in for startline f.read() so for endline
 in f.read() will start reading but find no data, am I right?

 Thanks, Jon.



Try something like:

show_ones = False

for line in f.read():
if line.find(2) != -1 or show_ones == True:
   print line
   show_ones = True
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread Bob Gailer
[snip]

now ponder this:

f=file(prueba.txt.log)
for startline in f:
if startline.find(2) != -1:
for endline in f:
print endline
# etc.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread Kent Johnson
jon vs. python wrote:
 Hi everyone,
 I have a file with this content:
 
 1
 1
 1
 1
 1
 1
 1
 2
 1
 1
 
 I wanted a little script that would print the line containing 2 and 
 every line containing 1 after it. I've tried this:
 
   def p():
 f = file(prueba.txt,'r')
 for startline in f.read():

As Bob pointed out, f.read() reads the entire file into a single string. 
Iterating over a string yields individual characters, not lines. So 
startline is actually a single character.

 if startline.find(2) != -1:

More simply:
   if 2 in startline:

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread Alan Gauld

jon vs. python [EMAIL PROTECTED] wrote in

 I wanted a little script that would print the line containing 2 
 and every
 line containing 1 after it. I've tried this:

 def p():
f = file(prueba.txt,'r')
for startline in f.read():
if startline.find(2) != -1:
print startline
for endline in f.read():
if endline.find(1) != -1:
print endline
break
f.close()

Its easier to iterate over the file itself

found2 = False
for line in file(prueba.txt):
 if '2' in line: found2 = True
 if found2: print line
 else: continue

Should be close.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested, line by line, file reading

2007-12-16 Thread Alan Gauld
Alan Gauld [EMAIL PROTECTED] wrote 

 found2 = False
 for line in file(prueba.txt):
 if '2' in line: found2 = True
 if found2: print line
 else: continue

Just after posting I realised it would be better to do:

found2 = False
for line in file(prueba.txt):
found2 = found2 or line.startswith('2')
if found2: print line

The continue was superfluous and the if test 
less efficient that the boolean test.
line.startswith seems a more appropriate test too, 
and should be more efficient on long lines.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line comments?

2007-06-07 Thread Khamid Nurdiev

You could use Kwrite and select the to be commented part and use the keys
Ctrl + D and to uncomment Ctrl + Shift + D.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line comments?

2007-06-07 Thread Alan Gauld
Brad Tompkins [EMAIL PROTECTED] wrote

 If there isn't a way, can someone recommend a text editor (I know 
 emacs and
 probably vi can do this, but they seem difficult to use) that will 
 comment
 out blocks of text automatically for me?

The Pythonwin IDE has the Edit-Source-Comment out region command
IDLE has Format-Comment out region

Both use the shortcut Alt+3

But usually long comments are better exposed as doc strings.
Comments should be reserved for explaining why you wrote
the code the way you did - unusual constructs etc, use docstrings to
explain what the code is for.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line comments?

2007-06-07 Thread Thorsten Kampe
* Brad Tompkins (Wed, 6 Jun 2007 16:41:31 -0700)
 Is there a way to make use of multi-line comments when programming using
 python?  Having to stick a # in front of every line gets pretty tedious when
 I want to make a comment more detailed than I normally would.
 
 If there isn't a way, can someone recommend a text editor (I know emacs and
 probably vi can do this, but they seem difficult to use) that will comment
 out blocks of text automatically for me?

EditPad Pro under Windows and Komodo Edit from ActiveState...

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multi-line comments?

2007-06-06 Thread Brad Tompkins

Hello everyone,

This may seem like a pretty basic question but it's driving me crazy.

Is there a way to make use of multi-line comments when programming using
python?  Having to stick a # in front of every line gets pretty tedious when
I want to make a comment more detailed than I normally would.

If there isn't a way, can someone recommend a text editor (I know emacs and
probably vi can do this, but they seem difficult to use) that will comment
out blocks of text automatically for me?

Thanks,

Brad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line comments?

2007-06-06 Thread Paulo Nuin
Hi Brad

Use something like this

'''your
comments
here'''

Three single quotes will do it.

HTH

Paulo

Brad Tompkins wrote:
 Hello everyone,

 This may seem like a pretty basic question but it's driving me crazy.

 Is there a way to make use of multi-line comments when programming 
 using python?  Having to stick a # in front of every line gets pretty 
 tedious when I want to make a comment more detailed than I normally 
 would.

 If there isn't a way, can someone recommend a text editor (I know 
 emacs and probably vi can do this, but they seem difficult to use) 
 that will comment out blocks of text automatically for me?

 Thanks,

 Brad
 

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line comments?

2007-06-06 Thread John Fouhy
On 07/06/07, Brad Tompkins [EMAIL PROTECTED] wrote:
 Is there a way to make use of multi-line comments when programming using
 python?  Having to stick a # in front of every line gets pretty tedious when
 I want to make a comment more detailed than I normally would.

 If there isn't a way, can someone recommend a text editor (I know emacs and
 probably vi can do this, but they seem difficult to use) that will comment
 out blocks of text automatically for me?

With emacs, you can highlight a region and choose Comment out region
from the menu bar.  With vi, to comment out the current line and the
next n, type   :,+ns/^/#/

But the real answer to your question is to use docstrings.  A
docstring is a multiline string (delimited by  ) at the start of
a block of code.  A typical python module might look like this:

--- foo.py ---
 Module for working with foos.

This module adds foo support to python.
etc.


class Foo(object):
Main foo class.

   More stuff.
   

   def useBar(self, bar):
   Apply this foo to a bar. 
---

Python's help system can then pick up the docstrings automatically.
eg, if I started the interpreter and typed 'import Foo', then
'help(Foo)' would give me the module docstring, 'help(Foo.Foo)' would
give me the class docstring, and so on.

Check out the source code for python modules on your system (in the
lib directory of your install) for lots of examples.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line comments?

2007-06-06 Thread roberto
take care about the first  MUST be indented at the appropiated
level, the end one and the comment body may be placed where u want

http://softwareetal.blogspot.com/2007/06/python-comments.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Command Line Promps

2007-06-03 Thread Jason Coggins
Is it possible to have a Python program issue a command line promp to the 
terminal while the program is running?

Jason___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Promps

2007-06-03 Thread Bob Gailer
Jason Coggins wrote:
 Is it possible to have a Python program issue a command line promp to 
 the terminal while the program is running?
See raw_input() and input() built-in functions.
  
-- 
Bob Gailer
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Promps

2007-06-03 Thread Bob Gailer
Please always reply to the list, not just me. We are all working on 
these questions and we all learn from them.

Jason Coggins wrote:
 These seem to be ways of getting imput from the user.  I do not want 
 to send a command line to the user (for example, in the form of a 
 question) and get the users input.

 I want the Python program to open a terminal (if need be) and send a 
 command to the computer (through the terminal) that the program is 
 running on.
I think what you really want is to have Python run another program. True?

(Not that it matters a lot but which OS are you running?)

See os.system() and os.popen()

 Sorry if I was not more clear on this earlier,
Well it is often hard to be clear, but it sure saves time and energy.

-- 
Bob Gailer
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Promps

2007-06-03 Thread Jason Coggins
I am using Linux and yes I am wanting the program to run another program.  I 
have tried these before but, if I remember correctly, these methods caused 
the original program to freeze while waiting on the spawned program to 
return a value (usually either true or false).  I am planning on having the 
program start another program and then exit the original program after the 
second program is started but before the second program ends.  I will take 
another look at these to see if I can work around the freezing problem 
because I have a little more experience then when I tried it the first time.

I used the reply button to send a reply to the first message.  I did not 
realize it would send the reply directly to you instead of the list.  I have 
tried to send this reply to the list.

Thanks,

Jason

- Original Message - 
From: Bob Gailer [EMAIL PROTECTED]
To: Jason Coggins [EMAIL PROTECTED]
Cc: tutor@python.org
Sent: Sunday, June 03, 2007 4:24 PM
Subject: Re: [Tutor] Command Line Promps


 Please always reply to the list, not just me. We are all working on these 
 questions and we all learn from them.

 Jason Coggins wrote:
 These seem to be ways of getting imput from the user.  I do not want to 
 send a command line to the user (for example, in the form of a question) 
 and get the users input.

 I want the Python program to open a terminal (if need be) and send a 
 command to the computer (through the terminal) that the program is 
 running on.
 I think what you really want is to have Python run another program. True?

 (Not that it matters a lot but which OS are you running?)

 See os.system() and os.popen()

 Sorry if I was not more clear on this earlier,
 Well it is often hard to be clear, but it sure saves time and energy.

 -- 
 Bob Gailer
 510-978-4454
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Promps

2007-06-03 Thread jim stockford

sounds like threading is a solution.

On Jun 3, 2007, at 2:05 PM, Jason Coggins wrote:

 I am using Linux and yes I am wanting the program to run another 
 program.  I
 have tried these before but, if I remember correctly, these methods 
 caused
 the original program to freeze while waiting on the spawned 
 program to
 return a value (usually either true or false).  I am planning on 
 having the
 program start another program and then exit the original program after 
 the
 second program is started but before the second program ends.  I will 
 take
 another look at these to see if I can work around the freezing 
 problem
 because I have a little more experience then when I tried it the first 
 time.

 I used the reply button to send a reply to the first message.  I did 
 not
 realize it would send the reply directly to you instead of the list.  
 I have
 tried to send this reply to the list.

 Thanks,

 Jason

 - Original Message -
 From: Bob Gailer [EMAIL PROTECTED]
 To: Jason Coggins [EMAIL PROTECTED]
 Cc: tutor@python.org
 Sent: Sunday, June 03, 2007 4:24 PM
 Subject: Re: [Tutor] Command Line Promps


 Please always reply to the list, not just me. We are all working on 
 these
 questions and we all learn from them.

 Jason Coggins wrote:
 These seem to be ways of getting imput from the user.  I do not want 
 to
 send a command line to the user (for example, in the form of a 
 question)
 and get the users input.

 I want the Python program to open a terminal (if need be) and send a
 command to the computer (through the terminal) that the program is
 running on.
 I think what you really want is to have Python run another program. 
 True?

 (Not that it matters a lot but which OS are you running?)

 See os.system() and os.popen()

 Sorry if I was not more clear on this earlier,
 Well it is often hard to be clear, but it sure saves time and energy.

 -- 
 Bob Gailer
 510-978-4454


 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command Line Promps

2007-06-03 Thread Alan Gauld
Jason Coggins [EMAIL PROTECTED] wrote

I am using Linux and yes I am wanting the program to run another 
program.  I
 have tried these before but, if I remember correctly, these methods 
 caused
 the original program to freeze while waiting on the spawned 
 program to
 return a value (usually either true or false).  I am planning on 
 having the
 program start another program and then exit the original program 
 after the
 second program is started but before the second program ends.

Since you are on Linux you should look at os.fork()

The use of fork() is covered in my tutorial in the topic on
Inter-Process Communications under the heading Spawning Processes.

 I used the reply button to send a reply to the first message.  I did 
 not
 realize it would send the reply directly to you instead of the list. 
 I have
 tried to send this reply to the list.

Reply All is the tool to use. Reply replies only to the sender which
is set to the original sender.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-14 Thread Alan Gauld

Teresa Stanton [EMAIL PROTECTED] wrote

 No one suggested this.  That's great! Wish I had seen it sooner. 
 Thanks,
 I'll put that in my notebook for further use later.

Note that Fileinput is used to iterate over a (set of) file line by 
line,
it doesn't read the entire file into a string as in your original
question. You can get round that by using join() to join the
lines togvether after reading.

Also there are no prompts to stdin if that matters.

HTH,

Alan G.


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-13 Thread Daniel Yoo
Hi Teresa,

Has anyone on this thread already suggested the 'fileinput' module?  From 
what I understand, what 'fileinput' does is exactly what you're asking 
from:

 http://mail.python.org/pipermail/tutor/2007-April/053669.html

Here's documentation on 'fileinput':

 http://www.python.org/doc/lib/module-fileinput.html


Good luck!
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-13 Thread Teresa Stanton
No one suggested this.  That's great! Wish I had seen it sooner.  Thanks,
I'll put that in my notebook for further use later.

 

-Original Message-
From: Daniel Yoo [mailto:[EMAIL PROTECTED] 
Sent: Friday, April 13, 2007 5:51 PM
To: [EMAIL PROTECTED]
Cc: [EMAIL PROTECTED]
Subject: RE: Command line args

Hi Teresa,

Has anyone on this thread already suggested the 'fileinput' module?  From
what I understand, what 'fileinput' does is exactly what you're asking
from:

 http://mail.python.org/pipermail/tutor/2007-April/053669.html

Here's documentation on 'fileinput':

 http://www.python.org/doc/lib/module-fileinput.html


Good luck!


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-10 Thread Alan Gauld
Kirk Bailey [EMAIL PROTECTED] wrote 

 Try:
 filename=sys.arv[1]
 except Exception, e:

This still doesn't help for the problem where a 
different exception is raised.It really does need to be

try: filename = sys.argv[1]:
except IndexError:


 if filename='':
 filename='foo' # define a default value
 else:
 if foo: # detect one likely error
 foobarcode
 else:

This is invalid syntax it would need to be a chain of if/elif/else

 another idea is simply detect that there IS a argument;
 
 if sys.argv[1];
 filename=sys.argv[1]
 ...
 which avoids try altogether. Somehow I kinda like this way more.

This would still throw an exception if argv[1] doesn't exist 
because the code still tries to access non existent data. 
You cannot get away without using the try/except here 
unless you check the length of argv:

if len(sys.argv)  1:
filename = sys.argv[1]

Now you can check whether filename is valid or not.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-09 Thread Luke Paireepinart
Kirk Bailey wrote:
 Teresa Stanton wrote:
   
 If one argument to a script is provided I am to take the input from it.  
 I figure that is presented like this:

 filename = sys.argv[1]
 
 Try:
   
the 'try' keyword is not capitalized in Python.
   filename=sys.arg[1]
 except exception, E:
   
you should only catch the exception you expect, so you don't 
accidentally silence an unrelated error.
so
except IndexError:
because you're trying to index into a list that might not have 2 or more 
elements.
   filename='FooBar'
   
You said you wanted the input from standard input, so just put a 
raw_input here.

so the new code is:

try: filename = sys.argv[1]
except IndexError: filename = raw_input(Prompt: )

HTH,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-09 Thread Kirk Bailey
ok, try this:

Try:
filename=sys.arv[1]
except Exception, e:
if filename='':
filename='foo'  # define a default value
else:
if foo: # detect one likely error
foobarcode
else:
if bar: # detect another one
morefoobarcode
else:   # final catchall for things you
# did not anticipate
Print 'how the heck did you accomplish this?!? I QUIT~!
sys.exit(13)

i has something vauely like this in the wiki on the slab right now, 
except it was addressing the query string. other than that, same problem.

another idea is simply detect that there IS a argument;

if sys.argv[1];
filename=sys.argv[1]
if condition:
do something
else:
do this instead
else:
filename=foo

which avoids try altogether. Somehow I kinda like this way more.



Luke Paireepinart wrote:
 Kirk Bailey wrote:
 Teresa Stanton wrote:
  
 If one argument to a script is provided I am to take the input from 
 it.  I figure that is presented like this:

 filename = sys.argv[1]
 
 Try:
   
 the 'try' keyword is not capitalized in Python.
 filename=sys.arg[1]
 except exception, E:
   
 you should only catch the exception you expect, so you don't 
 accidentally silence an unrelated error.
 so
 except IndexError:
 because you're trying to index into a list that might not have 2 or more 
 elements.
 filename='FooBar'
   
 You said you wanted the input from standard input, so just put a 
 raw_input here.
 
 so the new code is:
 
 try: filename = sys.argv[1]
 except IndexError: filename = raw_input(Prompt: )
 
 HTH,
 -Luke
 
 

-- 
Salute!
-Kirk Bailey
   Think
  +-+
  | BOX |
  +-+
   knihT

Fnord.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-08 Thread Kirk Bailey


Teresa Stanton wrote:
 If one argument to a script is provided I am to take the input from it.  
 I figure that is presented like this:
 
 filename = sys.argv[1]
Try:
filename=sys.arg[1]
except exception, E:
filename='FooBar'

 data = open(filename).read()
 
 But, if none are provided, input should come from standard input.  How 
 do I write that code?
 
 TY
 
 
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 
 
 
 No virus found in this incoming message.
 Checked by AVG Free Edition.
 Version: 7.5.446 / Virus Database: 269.0.0/750 - Release Date: 4/6/2007 9:30 
 PM

-- 
Salute!
-Kirk Bailey
   Think
  +-+
  | BOX |
  +-+
   knihT

Fnord.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-07 Thread Alan Gauld

Teresa Stanton [EMAIL PROTECTED] wrote

 If one argument to a script is provided I am to take the input from 
 it.

OK This sounds like a homework so I can't give you a direct
answer but only some things to consider.

 I figure that is presented like this:

 filename = sys.argv[1]
 data = open(filename).read()

So far so good but how will you know whether there is
anyting in sys.argv to read?

 But, if none are provided, input should come from standard input.

Standard input is where you normally get input in interactive 
programs.
How do you normally get a user to giove you information?

You'll find more about receiving input from users in the
Talking to the User topic of my tutorial.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line args

2007-04-07 Thread Andreas Kostyrka
* Teresa Stanton [EMAIL PROTECTED] [070407 18:52]:
If one argument to a script is provided I am to take the input from it.  I
figure that is presented like this:
 
filename = sys.argv[1]
data = open(filename).read()
 
But, if none are provided, input should come from standard input.  How do
I write that code?

if len(sys.argv)  1:
 fp = file(sys.argv[1])
else:
 fp = sys.stdin
data = fp.read()
if fp is not sys.stdin:
 fp.close()

Andreas
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multi-line code that uses \ in doctest

2007-02-06 Thread Don Taylor
When I try to use something like:

  hexStringNums = ('1', '2', '3', '4', '5', '6',\
...  '7', '8', '9','0')

or:

  for hexString in hexStrings:
... for x in hexString:
... if ((not x in hexStringChars) and
... (not x in hexStringNums)):
... print hexString+ \
...  is not a hex string.
... break

in doctest (Python 2.4) I get an invalid syntax error around the line 
continuation marker, e.g.

Failed example:
 hexStringNums = ('1', '2', '3', '4', '5', '6',... 
'7', '8', '9','0')
Exception raised:
 Traceback (most recent call last):
   File C:\PYTHON24\lib\doctest.py, line 1243, in __run
 compileflags, 1) in test.globs
   File doctest __main__[1], line 1
  hexStringNums = ('1', '2', '3', '4', '5', '6',... 
  '7', '8', '9','0')
^
  SyntaxError: invalid syntax

I can fix this by not using \ line continuations, but is there a way to 
get doctest to parse these lines as I expect?


Thanks,


Don Taylor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line code that uses \ in doctest

2007-02-06 Thread Kent Johnson
Don Taylor wrote:
 When I try to use something like:
 
   hexStringNums = ('1', '2', '3', '4', '5', '6',\
 ...  '7', '8', '9','0')
 
 or:
 
   for hexString in hexStrings:
 ... for x in hexString:
 ... if ((not x in hexStringChars) and
 ... (not x in hexStringNums)):
 ... print hexString+ \
 ...  is not a hex string.
 ... break
 
 in doctest (Python 2.4) I get an invalid syntax error around the line 
 continuation marker, e.g.
 
 Failed example:
  hexStringNums = ('1', '2', '3', '4', '5', '6',... 
 '7', '8', '9','0')
 Exception raised:
  Traceback (most recent call last):
File C:\PYTHON24\lib\doctest.py, line 1243, in __run
  compileflags, 1) in test.globs
File doctest __main__[1], line 1
   hexStringNums = ('1', '2', '3', '4', '5', '6',... 
   '7', '8', '9','0')
 ^
   SyntaxError: invalid syntax
 
 I can fix this by not using \ line continuations, but is there a way to 
 get doctest to parse these lines as I expect?

I think the problem is that the normal Python string processor (not 
doctest) is swallowing the \newline in the string. Try putting your 
doctest string in a raw string (r'') or double the backslash (\\).

This page has more details:
file:///C:/Python25/Doc/lib/doctest-finding-examples.html

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line code that uses \ in doctest

2007-02-06 Thread Kent Johnson
Kent Johnson wrote:
 This page has more details:
 file:///C:/Python25/Doc/lib/doctest-finding-examples.html

Oops. The on-line version of that is here:
file:///C:/Python25/Doc/lib/doctest-finding-examples.html

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line code that uses \ in doctest

2007-02-06 Thread Terry Carroll
On Tue, 6 Feb 2007, Kent Johnson wrote:

 Kent Johnson wrote:
  This page has more details:
  file:///C:/Python25/Doc/lib/doctest-finding-examples.html
 
 Oops. The on-line version of that is here:
 file:///C:/Python25/Doc/lib/doctest-finding-examples.html

http://www.python.org/doc/lib/doctest-finding-examples.html

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multi-line code that uses \ in doctest

2007-02-06 Thread Kent Johnson
Terry Carroll wrote:
 On Tue, 6 Feb 2007, Kent Johnson wrote:
 
 Kent Johnson wrote:
 This page has more details:
 file:///C:/Python25/Doc/lib/doctest-finding-examples.html
 Oops. The on-line version of that is here:
 file:///C:/Python25/Doc/lib/doctest-finding-examples.html
 
 http://www.python.org/doc/lib/doctest-finding-examples.html

=:-0

Not my day for external references...thanks.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a line

2006-11-07 Thread Alan Gauld
Linda,

- Original Message - 
 From: linda.s [EMAIL PROTECTED]
 To: Danny Yoo [EMAIL PROTECTED]
 Cc: Alan Gauld [EMAIL PROTECTED]; Tutor 
 tutor@python.org
 Sent: Tuesday, November 07, 2006 12:00 AM
 Subject: a line

I can't speak for Danny, but I'd apprreciate if you could just
post your questions to the tutor list and not CC Danny and
me. I suspect you are using an old thread entry to reply, but
nonetheless I get more than enough email as it is, thanks.

 What does
 Pythonw -i test.py -i
 do in Mac machine?

It executes pythonw with the -i option.
Pythonw then executes test.py passing it a -i option.

python -h

will get you a list of all the commandline switches.
-i forces python to end the program and stay in interactive mode
(the  prompt), which is very useful for debugging unusual faults.

pythonw runs without a console window.

I assume the same applies on the Mac although I've never
tried using pythonw on my Mac

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] a line

2006-11-06 Thread linda.s
What does
Pythonw -i test.py -i
do in Mac machine?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line arguments passing

2005-12-04 Thread Alan Gauld

 My question is: when invoking a program with, let's say, a filename
 containing spaces as a parameter:
 
 myprog -file Long name
 
 What does sys.argv hold in this case? 

What did you get when you tried it?

I  ran:

###test.py ##
import sys
print sys.argv

###

python test.py foo long name bar

and got
['testargv.py', 'foo', 'long name', 'bar']

What did you get? Since its much less typing to try it than to ask 
the question I assume you must have had a problem with it?

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



and got

I am specifically interested in
 whether argv[2]==\Long or argv[2]==Long name, that is, if the shell
 does the processing or I need to do it in the program. Also, I need to
 know if most environments do the same (I wouldn't want to be caught
 pants down while porting this to Windows).
 
 Many thanks in advance for your valuable suggestions and apologies if I
 have misposted,
 
 Vlad
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line arguments passing

2005-12-04 Thread Vlad Popescu
On Sat, 2005-12-03 at 17:23 -0800, Danny Yoo wrote:
 
   My question is: when invoking a program with, let's say, a filename
   containing spaces as a parameter:
  
   myprog -file Long name
  
   What does sys.argv hold in this case? I am specifically interested in
   whether argv[2]==\Long or argv[2]==Long name,
 
 
 Hi Vlad,
 
 What you're asking is a platform-specific thing.  I believe it should do
 what you're expecting --- Long name should be a pulled together as a
 single argument in sys.argv.  But it's not Python that's pulling Long
 name together: it's your operating system's command line shell that's
 doing this.
 
 For example, on Windows, the following pages:
 
 http://www.microsoft.com/technet/community/columns/scripts/sg0704.mspx
 http://www.microsoft.com/technet/archive/winntas/deploy/shellscr.mspx
 
 talk about how Windows does command line argument parsing.  (Search those
 pages for the word quote, and you'll see a mention of this.) And the
 details on the role of quoting arguments is simliar for Unix shells like
 'bash' or 'tcsh'.  For example, for the bash shell:
 
 http://www.gnu.org/software/bash/manual/bashref.html#SEC8
 
 
 So all Python knows is that it's getting an array of strings: it doesn't
 even see the original line that the user typed at the command line prompt;
 it instead gets something that has already been partially digested by your
 command line shell.
 
 
 Hope this helps!
 
Thanks, that's what I was looking for -- a multiplatform reference,
since I can't test scripts on Windows just yet.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line arguments passing

2005-12-04 Thread Vlad Popescu
I don't have Python on Windows and didn't want to make any assumptions
about the way the Windows shell passes parameters. Sorry again for being
trivial.

On Sun, 2005-12-04 at 09:00 +, Alan Gauld wrote:
  My question is: when invoking a program with, let's say, a filename
  containing spaces as a parameter:
  
  myprog -file Long name
  
  What does sys.argv hold in this case? 
 
 What did you get when you tried it?
 
 I  ran:
 
 ###test.py ##
 import sys
 print sys.argv
 
 ###
 
 python test.py foo long name bar
 
 and got
 ['testargv.py', 'foo', 'long name', 'bar']
 
 What did you get? Since its much less typing to try it than to ask 
 the question I assume you must have had a problem with it?
 
 Alan G
 Author of the learn to program web tutor
 http://www.freenetpages.co.uk/hp/alan.gauld
 
 
 
 and got
 
 I am specifically interested in
  whether argv[2]==\Long or argv[2]==Long name, that is, if the shell
  does the processing or I need to do it in the program. Also, I need to
  know if most environments do the same (I wouldn't want to be caught
  pants down while porting this to Windows).
  
  Many thanks in advance for your valuable suggestions and apologies if I
  have misposted,
  
  Vlad
  
  
  
 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Command line arguments passing

2005-12-03 Thread Vlad Popescu
Hi there, everyone; first time poster! Sorry if this isn't very closely
related to Python, but I have encountered the issue while trying to
learn Python, so I guess I can just ask here.

My question is: when invoking a program with, let's say, a filename
containing spaces as a parameter:

myprog -file Long name

What does sys.argv hold in this case? I am specifically interested in
whether argv[2]==\Long or argv[2]==Long name, that is, if the shell
does the processing or I need to do it in the program. Also, I need to
know if most environments do the same (I wouldn't want to be caught
pants down while porting this to Windows).

Many thanks in advance for your valuable suggestions and apologies if I
have misposted,

Vlad


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line arguments passing

2005-12-03 Thread Christopher Arndt
Vlad Popescu schrieb:
 Hi there, everyone; first time poster! Sorry if this isn't very closely
 related to Python, but I have encountered the issue while trying to
 learn Python, so I guess I can just ask here.
 
 My question is: when invoking a program with, let's say, a filename
 containing spaces as a parameter:
 
 myprog -file Long name
 
 What does sys.argv hold in this case? I am specifically interested in
 whether argv[2]==\Long or argv[2]==Long name, 

Why don't you just try it out?

$ python - -f Long file
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 import sys
 print sys.argv[1]
-f
 print sys.argv[2]
...

I think you can do the rest.

Chris
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Command line arguments passing

2005-12-03 Thread Danny Yoo


  My question is: when invoking a program with, let's say, a filename
  containing spaces as a parameter:
 
  myprog -file Long name
 
  What does sys.argv hold in this case? I am specifically interested in
  whether argv[2]==\Long or argv[2]==Long name,


Hi Vlad,

What you're asking is a platform-specific thing.  I believe it should do
what you're expecting --- Long name should be a pulled together as a
single argument in sys.argv.  But it's not Python that's pulling Long
name together: it's your operating system's command line shell that's
doing this.

For example, on Windows, the following pages:

http://www.microsoft.com/technet/community/columns/scripts/sg0704.mspx
http://www.microsoft.com/technet/archive/winntas/deploy/shellscr.mspx

talk about how Windows does command line argument parsing.  (Search those
pages for the word quote, and you'll see a mention of this.) And the
details on the role of quoting arguments is simliar for Unix shells like
'bash' or 'tcsh'.  For example, for the bash shell:

http://www.gnu.org/software/bash/manual/bashref.html#SEC8


So all Python knows is that it's getting an array of strings: it doesn't
even see the original line that the user typed at the command line prompt;
it instead gets something that has already been partially digested by your
command line shell.


Hope this helps!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-06 Thread Christian Meesters
Hi,
Great! My own solution was more like Wolfram's. But your solution, 
Pierre, really runs under obfuscating enhanced. I like it. And your 
idea, Andrei, is something I really didn't expect.
Anyway, sorry for my late reply. Guess I learned a lot again.

Thanks,
Christian
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-05 Thread alan . gauld

This is a perfect opportunity to give the reminder that the
conversion 
functions are also types that can be used more transparently for such

Neat I didn't know\ that. How dioes Python equate a function object
to a type? Is it hard wired?

  [(type(x)==int and float(x) or x) for x in l]
['foo', 0]
  # notice that 0 is still an int, not a float
  [(type(x)==int and [float(x)] or [x])[0] for x in l]
['foo', 0.0]
  # ok, that's better

And a nice subtle catch.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-05 Thread Pierre Barbier de Reuille

[EMAIL PROTECTED] a écrit :
This is a perfect opportunity to give the reminder that the
conversion 
functions are also types that can be used more transparently for such

Neat I didn't know\ that. How dioes Python equate a function object
to a type? Is it hard wired?
No, you see it the wrong way !
int is a type, not a function ! But, in Python, types append to be 
callable (ie. to behave like functions). For example when you define a 
class Foo with :

class Foo:
  def __init__(self):
pass
Foo is a type but you can also *call* Foo with :
f = Foo()
But this construct an object (and involves many function calls) and is 
not a simple function call.
So there is no need to hardwire that kind of things (even if it _may_ be 
hardwired to improve efficiency).

--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-05 Thread Kent Johnson
Pierre Barbier de Reuille wrote:
[EMAIL PROTECTED] a écrit :
This is a perfect opportunity to give the reminder that the
conversion functions are also types that can be used more 
transparently for such
Neat I didn't know\ that. How dioes Python equate a function object
to a type? Is it hard wired?
No, you see it the wrong way !
int is a type, not a function ! But, in Python, types append to be 
callable (ie. to behave like functions). 
Yes, that's right. int was changed from a function to a type in Python 2.2 as part of the 
introduction of new-style classes. See
http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION00031

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-05 Thread Gregor Lingl

Pierre Barbier de Reuille schrieb:
Mmmhhh ... not strictly one line but ...
import re
float_str = re.compile(r^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$)
val = [ ( (float_str.match(s) and [float(s)]) or [s])[0] for s in l2 ]
It's not really readable but well ... it works ^_^
Pierre
This can be done in strictly 1 line (having already imported re):
 l = ['1','2','3','abc','0', '','4']
 [(re.match(r^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$,s) 
and [float(s)] or [s])[0] for s in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]

or, if one doesn't have to take into account exponential format:
 [(x and not[y for y in x if y not in 0123456789.] and 
x.count(.)2 and [float(x)] or [x])[0] for x in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]


hmmm, unfortunately Useless Python isn't maintained anymore...
(^o^)
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] one line code

2005-04-04 Thread Christian Meesters
Hi
Yesterday night I was thinking about the following problem:
I do have a list like l = ['1','2','3','abc','','4'] - for instance 
like a list one could get from a file import with the csv module (which 
is where my 'problem' comes from). Now I would like to generate the 
following list, preferably with one line of code:
l2 = [1.0,2.0,3.0,'abc','',4.0]
With other words I'd like to tell Python: Convert into a float if 
possible, otherwise append anyway. Is this possible in one line? (Right 
now my code is a lot longer.)
I was trying with 'filter' + lambda forms, list comprehensions etc., 
but could not find a solution. Could it be that a C-like solution with 
'?' and ':' is more straightforward than a solution with Python or am I 
just too blind to see a real pythonic solution here?

I am aware that putting a solution in one line of code might be against 
the 'Zen of Python' (... Complex is better than complicated ... 
Readability counts ...), but since I'm just asking out of curiosity, 
perhaps I'll get an answer anyway. ;-)

Thanks a lot in advance.
Cheers
Christian
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-04 Thread Alan Gauld
 With other words I'd like to tell Python: Convert into a float if 
 possible, otherwise append anyway. 

[ (type(x) == type(5) and float(x) or x) for x in mylist ]

Should do it...

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-04 Thread Liam Clarke
[(eval(compile('exec try:t=float(%s)\nexcept:t=%s  in
globals(),locals()'%(s,s),'','exec')),t)[1] for s in l]

Now that's ugly.



On Apr 5, 2005 9:51 AM, Alan Gauld [EMAIL PROTECTED] wrote:
  With other words I'd like to tell Python: Convert into a float if
  possible, otherwise append anyway.
 
 [ (type(x) == type(5) and float(x) or x) for x in mylist ]
 
 Should do it...
 
 Alan G.
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-04 Thread C Smith
From: Alan Gauld [EMAIL PROTECTED]
With other words I'd like to tell Python: Convert into a float if
possible, otherwise append anyway.
[ (type(x) == type(5) and float(x) or x) for x in mylist ]
This is a perfect opportunity to give the reminder that the conversion 
functions are also types that can be used more transparently for such 
type tests:

###
 type(int)
type 'type'
 type(1)==int
True
 type(1)==float
False
###
If you really want a float and not an int then you should use the 
following 1-liner as suggested by the programming FAQ 1.2.11 ( 
http://www.python.org/doc/faq/programming.html ):

[ (type(x) == int and [float(x)] or [x])[0] for x in mylist]
###
 l=['foo', 0]
 [(type(x)==int and float(x) or x) for x in l]
['foo', 0]
 # notice that 0 is still an int, not a float
 [(type(x)==int and [float(x)] or [x])[0] for x in l]
['foo', 0.0]
 # ok, that's better
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] read line x from a file

2005-01-22 Thread Kent Johnson
Jay Loden wrote:
One simple solution is to do: 

fle = open(file)
contents = file.readlines()
file.close()
print contents[x]  #or store this in a variable, whatever
That is the simplest solution. If your file gets bigger and you don't want to read it all at once, 
you can use enumerate to iterate the lines and pick out the one you want:

f = open(...)
for i, line in enumerate(f):
  if i==targetLine:
print line # or whatever
break
f.close()
BTW try to avoid using 'file' as the name of a variable, it is a builtin 
function (or type, actually).
Kent
-Jay
On Friday 21 January 2005 11:22, J. M. Strother wrote:
I have  a text file containing 336 records.
I can read and print out the whole file without any problem.
What I want to do is read and print out one record only (chosen at
random). So I need to get to record x, select it, and then print it (or
store it in a variable).
Can anyone tell me now to do this?
I'm new to Python and programming, so sorry if this is very basic. Thanks.
jon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >