Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Cameron Simpson
Hi Bob,

I notice your problem is solved, but I've got a few remarks about
your script and also how you might have investigated your problem.

First: the os.foo calls are usually very thin wrappers for the
corresponding OS call. So if you get an errno type error for
os.symlink, it is worth running:

  man 2 symlink

to read the man page for the symlink OS call. Amongst other things
it says, under ERRORS:

  ENOENT A directory component in newpath does not exist or is a dangling
 symbolic link, or oldpath is the empty string.

You need to know that ENOENT is errno 2 "No such file or directory",
but it helps.

The other things are just script remarks, not directly related to your problem:

On 24Feb2014 16:07, Bob Williams  wrote:
> if pathList[j][-3:] == "mp3":

This is often written (I've inserted a dot, assuming you don't want
"foomp3", only "foo.mp3"):

  if pathList[j].endswith(".mp3"):

More readable, and also more reliable because it doesn't rely on
you getting the "3" correct.

> linkName1 = pathList[j][0:-3] + "mp3"

Isn't this exactly the same as pathList[j] ?

> linkName2 = destPath + linkName1[len(sourcePath):]

You might want to spell this:

  linkName2 = os.path.join(destPath, linkName1[len(sourcePath):])

This means you don't need to have trailing slashes on sourcePath and
destPath. And, to a degree, it might work on non-UNIX systems where
the path separator is not a slash. Ireelevant for you now, but it
is often a good habit to use portable ways of working on things if
it is not inconvenient.

[...snip...]
> I have tried escaping the spaces with '\', but the same error is
> generated.

This is usually never the right thing to do. If you find yourself
doing this, chances are you're trying to fix the wrong thing. You
only need to escape strings when passing them to something that
will be interpreting a line of text. Such as a piece of shell script.
You should not need it to pass strings to something that expects
strings.

Cheers,
-- 
Cameron Simpson 

We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil. - Donald Knuth
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.call list vs. str argument

2014-02-26 Thread Albert-Jan Roskam

Regards,

Albert-Jan



~~

All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 

fresh water system, and public health, what have the Romans ever done for us?

~~


On Tue, 2/25/14, eryksun  wrote:

 Subject: Re: [Tutor] subprocess.call list vs. str argument
 To: "Dave Angel" 
 Cc: tutor@python.org
 Date: Tuesday, February 25, 2014, 11:30 PM
 
 On Tue, Feb 25, 2014 at 4:54 PM, Dave
 Angel 
 wrote:
 > CreateProcess has its own design bobbles as well. For
 example,  if
 > you forget to put quotes around the program name, 
 it will
 > happily try to add ".exe" to *multiple* places in the
 hopes that
 > one of them will work.
 >
 > Adding a file c:\program.exe to a system will blow up
 lots of
 > programs that were working by mistake for years.
 
 

Yesterday evening (it was *late* so forgive me if I wrong) I realized that part 
of my confusion was also caused by the fact that I ran my code in Idle.
If I called subprocess.call with a list argument, it  returned code 0 (success) 
but the generated sphinx code was not the same as when I ran the program from 
the terminal. I concluded that this is some weird interaction between Idle 
(which may also run in a subprocess??) and my own program. I also had no 
problems when I ran (in the terminal): python -c "import subprocess; 
subprocess.call(['sphinx-apidoc'...(etc)])"

I was surprised that the list elements of the argument for subprocess.call 
*have to be* separate tokens, e.g. (earlier in one of Danny's replies): a token 
(list element) '-f -F' won't work, it has to be two separate elements/tokens: 
'-f', '-F'. Apparently, subprocess.call is more than just a convenience 
function that " ".joins the list and escapes the resulting string.

regards,
Albert-Jan




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


Re: [Tutor] Responding Tweet: A Twitter Bot

2014-02-26 Thread Zaki Akhmad
On Fri, Feb 21, 2014 at 4:05 PM, Walter Prins  wrote:
>
> With the caveat that I'm not familiar with the Twitter streaming API's
> and that I literally only spend 3 minutes googling this, it seems to
> me to be the case that the Twitter streaming API's is intended to be a
> push style notification service.
>
> This means you should not in principle ideally be polling the service
> for updates yourself (e.g. using sleep/crong etc).  Instead, the docs
> say that the streaming API can return an iterator that yields objects
> as they're decoded from the stream.  Quote:
>
> "The TwitterStream object is an interface to the Twitter Stream API
> (stream.twitter.com). This can be used pretty much the same as the
> Twitter class except the result of calling a method will be an
> iterator that yields objects decoded from the stream. For example::"
>
> It's highly preferable to not poll something if it will
> generate/notify you of new objects, so you should be able to do
> something like in their example.  Quote:
>
> twitter_stream = TwitterStream(auth=UserPassAuth('joe', 'joespassword'))
> iterator = twitter_stream.statuses.sample()
>
> for tweet in iterator:
> # ...do something with this tweet... (e.g. check if you want to
> retweet or something)
>
> So the for loop should just block by itself until a new tweet/message
> comes in at which point it will spring to life and hand it to your
> code to process.
>
> I hope that helps, and apologies if I misunderstood something or have
> missed something that makes my comment irrelevant to your problem.

Hi Lists,

Finally, I could monitor in real time by accessing Twitter API
Stream[1]. I add the track variable to string which I'd like to
monitor. Such as @mention.

for tweet in twitter_stream.statuses.filter(track='example'):
print tweet

I use Mike Verdone's Twitter python library[2]

[1]https://dev.twitter.com/docs/api/1.1/post/statuses/filter
[2]https://pypi.python.org/pypi/twitter/1.13.1

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


[Tutor] next element in list

2014-02-26 Thread rahmad akbar
hey guys

i have this file i wish to parse, the file looks something like bellow.
there are only four entry here (AaaI, AacLI, AaeI, AagI). the complete file
contains thousands of entries

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
REBASE, The Restriction Enzyme Database   http://rebase.neb.com
Copyright (c)  Dr. Richard J. Roberts, 2014.   All rights reserved.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Rich RobertsJan 30 2014

AaaI (XmaIII) C^GGCCG
AacLI (BamHI) GGATCC
AaeI (BamHI)  GGATCC
AagI (ClaI)   AT^CGAT


the strategy was to mark the string 'Rich Roberts' as the start. i wrote
the following function. but then i realized i couldn't do something like
.next() to the var in_file which is a list. so i added a flag start = False
in which will be turned to True upon 'Rich Roberts' found. is the any
simpler way to move to the next element in the list. like built in method
or something like that.

def read_bionet(bionetfile):
  res_enzime_dict = {}
  in_file = open(bionetfile, 'r').readlines()
  start = False
  for line in in_file:
if line.startswith('Rich Roberts'):
  start = True
if start and len(line) >= 10:
line = line.split()
res_enzime_dict[line[0]] = line[-1]
  return res_enzime_dict


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


Re: [Tutor] next element in list

2014-02-26 Thread Dave Angel
 rahmad akbar  Wrote in message:
>
> 
 then i realized i couldn't do something like .next() to the var in_file which 
is a list. so i added a flag start = False in which will be turned to True upon 
'Rich Roberts' found. is the any simpler way to move to the next element in the 
list. like built in method or something like that. 

def read_bionet(bionetfile):
  res_enzime_dict = {}
  in_file = open(bionetfile, 'r').readlines()
  start = False
  for line in in_file:
    if line.startswith('Rich Roberts'):



If you omit the call to readlines,  then in_file is a file object
 instead of a list. A file object is its own iterator,  and has a
 next () method.  You could also change readlines to xreadlines
 but I don't see the advantage. 

Another plus is saving all that memory that a list would take.
-- 
DaveA

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


Re: [Tutor] calling global in funtions.

2014-02-26 Thread Dave Angel
 Santosh Kumar  Wrote in message:
>
 Requirement : i want to call a variable assigned outside a function scope 
anytime 
>  within the function. I read "global" is a way. 
> 

Your sample code doesn't do any calling.  But if your design
 requires you to assign to a global from inside a function,  then
 the global declaration is the correct way. And the global
 statement should be at the beginning of the function.
 

-- 
DaveA

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


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread David
On 26 February 2014 16:31, Cameron Simpson  wrote:
>
> You need to know that ENOENT is errno 2 "No such file or directory",
> but it helps.

In case it helps anyone, there is information in the python
documentation of the errno module that associates system error numbers
with their corresponding messages. Same as in 'man 3 errno' .
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] next element in list

2014-02-26 Thread Peter Otten
rahmad akbar wrote:

> hey guys
> 
> i have this file i wish to parse, the file looks something like bellow.
> there are only four entry here (AaaI, AacLI, AaeI, AagI). the complete
> file contains thousands of entries
> 
> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> REBASE, The Restriction Enzyme Database   http://rebase.neb.com
> Copyright (c)  Dr. Richard J. Roberts, 2014.   All rights reserved.
> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> 
> Rich RobertsJan 30
> 2014
> 
> AaaI (XmaIII) C^GGCCG
> AacLI (BamHI) GGATCC
> AaeI (BamHI)  GGATCC
> AagI (ClaI)   AT^CGAT
> 
> 
> the strategy was to mark the string 'Rich Roberts' as the start. i wrote
> the following function. but then i realized i couldn't do something like
> .next() to the var in_file which is a list. so i added a flag start =
> False in which will be turned to True upon 'Rich Roberts' found. is the
> any simpler way to move to the next element in the list. like built in
> method or something like that.
> 
> def read_bionet(bionetfile):
>   res_enzime_dict = {}
>   in_file = open(bionetfile, 'r').readlines()
>   start = False
>   for line in in_file:
> if line.startswith('Rich Roberts'):
>   start = True
> if start and len(line) >= 10:
> line = line.split()
> res_enzime_dict[line[0]] = line[-1]
>   return res_enzime_dict

As David says, don't call readlines() which reads the lines of the file into 
a list, iterate over the file directly:

def read_bionet(bionetfile):
with open(bionetfile) as in_file:
# skip header
for line in in_file:
if line.startswith("Rich Roberts"):
break

# populate dict
res_enzimes = {}
for line in in_file: # continues after the line with R. R.
if len(line) >= 10:
parts = line.split()
res_enzimes[parts[0]] = parts[-1]

# file will be closed now rather than at 
# the garbage collector's discretion

return res_enzimes


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


Re: [Tutor] next element in list

2014-02-26 Thread rahmad akbar
David, Peter

roger that and thanks so much!!


On Wed, Feb 26, 2014 at 1:29 PM, Peter Otten <__pete...@web.de> wrote:

> rahmad akbar wrote:
>
> > hey guys
> >
> > i have this file i wish to parse, the file looks something like bellow.
> > there are only four entry here (AaaI, AacLI, AaeI, AagI). the complete
> > file contains thousands of entries
> >
> > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> > REBASE, The Restriction Enzyme Database   http://rebase.neb.com
> > Copyright (c)  Dr. Richard J. Roberts, 2014.   All rights reserved.
> > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> >
> > Rich RobertsJan 30
> > 2014
> >
> > AaaI (XmaIII) C^GGCCG
> > AacLI (BamHI) GGATCC
> > AaeI (BamHI)  GGATCC
> > AagI (ClaI)   AT^CGAT
> >
> >
> > the strategy was to mark the string 'Rich Roberts' as the start. i wrote
> > the following function. but then i realized i couldn't do something like
> > .next() to the var in_file which is a list. so i added a flag start =
> > False in which will be turned to True upon 'Rich Roberts' found. is the
> > any simpler way to move to the next element in the list. like built in
> > method or something like that.
> >
> > def read_bionet(bionetfile):
> >   res_enzime_dict = {}
> >   in_file = open(bionetfile, 'r').readlines()
> >   start = False
> >   for line in in_file:
> > if line.startswith('Rich Roberts'):
> >   start = True
> > if start and len(line) >= 10:
> > line = line.split()
> > res_enzime_dict[line[0]] = line[-1]
> >   return res_enzime_dict
>
> As David says, don't call readlines() which reads the lines of the file
> into
> a list, iterate over the file directly:
>
> def read_bionet(bionetfile):
> with open(bionetfile) as in_file:
> # skip header
> for line in in_file:
> if line.startswith("Rich Roberts"):
> break
>
> # populate dict
> res_enzimes = {}
> for line in in_file: # continues after the line with R. R.
> if len(line) >= 10:
> parts = line.split()
> res_enzimes[parts[0]] = parts[-1]
>
> # file will be closed now rather than at
> # the garbage collector's discretion
>
> return res_enzimes
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] subprocess.call list vs. str argument

2014-02-26 Thread eryksun
On Wed, Feb 26, 2014 at 3:50 AM, Albert-Jan Roskam  wrote:
> On Tue, Feb 25, 2014 at 4:54 PM, Dave Angel  wrote:
>> CreateProcess has its own design bobbles as well. For
>> example,  if you forget to put quotes around the program
>> name, it will happily try to add ".exe" to *multiple*
>> places in the hopes that one of them will work.
>> Adding a file c:\program.exe to a system will blow up
>> lots of programs that were working by mistake for years.
>
> Yesterday evening (it was *late* so forgive me if I wrong) I
> realized that part of my confusion was also caused by the fact
> that I ran my code in Idle. If I called subprocess.call with a
> list argument, it returned code 0 (success) but the generated
> sphinx code was not the same as when I ran the program from
> the terminal. I concluded that this is some weird interaction
> between Idle (which may also run in a subprocess??) and my own
> program. I also had no problems when I ran (in the terminal):
> python -c "import subprocess;
> subprocess.call(['sphinx-apidoc'...(etc)])"

Run IDLE from the terminal to have sphinx-apidoc inherit the terminal
for standard I/O. Then you can see the TTY output. I assume you're
using a POSIX system. I tacked on the bit about Windows CreateProcess
just so you'd be aware of the differences.

I'd flip the quoting around in a POSIX shell: python -c 'import
subprocess; subprocess.call(["sphinx-apidoc", "..."])'.

The shell expands $ and `cmd` in a double-quoted string:

$ msg=spam
$ echo "$msg"
spam
$ echo "`uname -o`"
GNU/Linux

But not in a single-quoted string:

$ echo '$msg'
$msg
$ echo '`uname -o`'
`uname -o`

> I was surprised that the list elements of the argument for
> subprocess.call *have to be* separate tokens, e.g. (earlier in
> one of Danny's replies): a token (list element) '-f -F' won't
> work, it has to be two separate elements/tokens: '-f', '-F'.
> Apparently, subprocess.call is more than just a convenience
> function that " ".joins the list and escapes the resulting
> string.

subprocess.call doesn't join the arguments:

def call(*popenargs, **kwargs):
return Popen(*popenargs, **kwargs).wait()

On a POSIX system, Popen._execute_child doesn't join the arguments,
either. It sets executable=args[0] and calls os.execvp(executable,
args) in the forked child process. If executable is a relative path,
os.execvp uses a loop over the paths in the PATH environment variable
to create an absolute path.

In CPython, os.execvp calls posix.execv(path, args), which is written
in C to call the system function execv(const char *path, char *const
argv[]). This replaces the current process image with the executable
file located at the absolute `path`.

To set up the system call, posix.execv transforms the tuple/list of
args into an array of char * pointers of length len(args) + 1. The
final item of the array is the NULL terminator. Any unicode strings
are encoded with the file-system encoding (probably UTF-8).

If the new process image isn't successfully executed (replacing Python
in the process), then OSError is raised. This is in the forked child,
so Popen._execute_child has to pickle the exception and write it back
to the parent process via os.write(errpipe_write,
pickle.dumps(exc_value)). It reads the `data` from the other end of
the pipe in the parent, and if it's non-empty it'll `raise
pickle.loads(data)`. That's the source of the OSError from calling
subprocess.call(cmd), where cmd was the entire command line as a
string.

As to what a program does if you mash two options into a single item
of its argv array, such as '-f -F', assuming it isn't trying to be
clever and expects the command-line to be parsed by a standard POSIX
shell, then '-f -F' won't match any of its known options.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] viewkeys,viewvalues,viewitems : Use Cases

2014-02-26 Thread Alan Gauld

On 26/02/14 07:04, Santosh Kumar wrote:


I defined a dictionary a below.

In [14]: a = {'a':1,'b':2,'c':3}
...
Funtion associated with dictionaries.

In [11]: print a.viewkeys()
dict_keys(['a', 'c', 'b'])

In [12]: print a.viewvalues()
dict_values([1, 3, 2])

In [13]: print a.viewitems()
dict_items([('a', 1), ('c', 3), ('b', 2)])

Where do i use these , can i get any user cases.


What is 'these'?
Do you mean:

1) where do I use a dictionary?
2) where do I use viewXXX()?
3) How do viewXXX differ from XXX (eg a.viewkeys v a.keys)?

I'm not sure which aspect you want help with?

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] calling global in funtions.

2014-02-26 Thread Alan Gauld

On 26/02/14 07:12, Santosh Kumar wrote:

All,

Requirement : i want to call a variable assigned outside a function
scope anytime within the function.


call in Python means something very specific, namey that you put parens 
after the name and that hopefully results in some code being executed.

You call dir by writing dir().

I assume you just mean you want to access a global variable (which is 
usually a bad idea and its better to pass it in/out of your function)




I read "global" is a way.


Yes, you specify that the variable is global using the global keyword

global a



a) Case I looks fine.


Yes, that's the correct usage.


b) Case II is bombing out.
CASE II:

In [21]: a = 10

In [22]: def fun_local():
: a = 5


This creates a new local variable 'a' in your function.


: print "the value of a is %d" %(a)
: global a
> :4: SyntaxWarning: name 'a' is assigned to before global 
declaration


This tries to tell the function that 'a' is global but it already has a 
local 'a' so if this worked you would lose that local variable. So 
Python issues a warning to tell you so. You must specify global before 
Python tries to create a local variable of the same name.


And if you are just reading the value then you don't need to specify 
global at all, you can just read it and Python will find it. But it's 
still better practice to pass the value in as an argument than to use 
globals.



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] calling global in funtions.

2014-02-26 Thread Steven D'Aprano
On Wed, Feb 26, 2014 at 12:42:00PM +0530, Santosh Kumar wrote:
> All,
> 
> Requirement : i want to call a variable assigned outside a function scope
> anytime within the function. I read "global" is a way.

You can *read* the value of a global from inside a function without 
needing to declare it at any time. In fact, this is how you can call 
other functions -- they are just globals that you read.

So this will work:

a = 10

def func():
print("a equals %s" % a)

func()
=> prints "a equals 10"



But if you want to re-assign a global, you need to declare it global 
first. By default, if you say "x = ..." inside a function, Python will 
treat that variable x as a local variable. So here's an example:

a = 10

def func():
global a
print("Before, a equals %s" % a)
a = 23
print("After, a equals %s" % a)


func()
=> prints "Before, a equals 10" and "After, a equals 23")


> a) Case I looks fine.
> b) Case II is bombing out.

Actually no it isn't. You're just getting a warning, not an error. See 
below.


> Is this how it works or please correct me if i am wrong.
> 
> case I:
> 
> In [17]: a = 10
> 
> In [19]: def fun_local():
>: global a
>: print "the value of a is %d" %(a)
>: a = 5
>: print "the value of a is %d" %(a)
>:
> 
> In [20]: fun_local()
> the value of a is 10
> the value of a is 5

This is completely fine.



> CASE II:
> 
> In [21]: a = 10
> 
> In [22]: def fun_local():
>: a = 5
>: print "the value of a is %d" %(a)
>: global a
> :4: SyntaxWarning: name 'a' is assigned to before global declaration
> :4: SyntaxWarning: name 'a' is assigned to before global declaration
> :4: SyntaxWarning: name 'a' is assigned to before global declaration

This is just a warning. It is STRONGLY RECOMMENDED that you put the 
global declaration at the top of the function, but it is not compulsary. 
If you put it somewhere else, you will get a warning, but the function 
will still work.

For now. Some day Python may change that behaviour, so it is safest if 
you move the global to the top of the function.


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


Re: [Tutor] When to use multiprocessing Managers?

2014-02-26 Thread David Palao
2014-02-25 11:52 GMT+01:00 James Chapman :
> Hello tutors
>
> I'm curious about managers and when to use them.
> For example, I see they offer a Queue() for sharing a Q between
> processes, but if I create a Q in the parent process and pass it down
> to child processes, then they can put messages into that Q just fine,
> and I presume the same thing for other objects available under the
> managers package.
>
> So unless the other process is on a different machine, is there a
> reason to use a manager?
>
> Does anyone have any use case examples or snippets I could look at even?
>
> Thanks in advance
> James
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Hello,
I asked myself the same question when I started using multiprocessing
time ago. So I was very happy when I saw the question by James.

>From my limited knowledge, I would say that a Manager can be useful
when processes are distributed across different hosts, or if the
exchange of information between processes is more complex than just a
couple of synchronization primitives.

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


Re: [Tutor] subprocess.call list vs. str argument

2014-02-26 Thread Oscar Benjamin
On 26 February 2014 08:50, Albert-Jan Roskam  wrote:
>
> Yesterday evening (it was *late* so forgive me if I wrong) I realized that 
> part of my confusion was also caused by the fact that I ran my code in Idle.
> If I called subprocess.call with a list argument, it  returned code 0 
> (success) but the generated sphinx code was not the same as when I ran the 
> program from the terminal. I concluded that this is some weird interaction 
> between Idle (which may also run in a subprocess??) and my own program. I 
> also had no problems when I ran (in the terminal): python -c "import 
> subprocess; subprocess.call(['sphinx-apidoc'...(etc)])"
>
> I was surprised that the list elements of the argument for subprocess.call 
> *have to be* separate tokens, e.g. (earlier in one of Danny's replies): a 
> token (list element) '-f -F' won't work, it has to be two separate 
> elements/tokens: '-f', '-F'. Apparently, subprocess.call is more than just a 
> convenience function that " ".joins the list and escapes the resulting string.

At the operating system level there is no "command line" as such on
posix (Linux, Mac etc.). The command to run a program is a string
giving the name of the program and you can also pass a list of strings
to the program as "arguments". The command line is something that
happens in the shell (e.g. bash). Whereas Python would use quotes and
commas to separate strings in a list of strings the shell just assumes
that whitespace separates strings.

So in Python you would write
['qwe', 'asd', 'zxc zxc']
and it's clear that you have a list of three strings. In the shell
(e.g. bash) you would type
qwe asd "zxc zxc"
and the shell understands that as three separate strings. The quotes
are needed to distinguish it from 4 strings because shell syntax
assumes that spaces separate strings.

So the idea of the "command line" as a single string that must be
split on whitespace is just something that happens in the shell. It is
supposed to be a convenient way of typing commands in the interactive
shell i.e. it would slow me down if I has to put in square brackets
quotes and commas every time I wanted to type a command in the shell
like ['ls', '-l', '~/mystuff']. But this convenience comes at a price
in that it becomes hard to handle strings that have spaces in them.
I've never really figured out how to write a non-trivial shell script
that can properly handle whitespace (it's easier to just avoid putting
spaces in filenames - or write the script in Python).

So really I think it's a good thing that Python lets you clearly
delineate each string in the argument list:
subprocess.call(['ls', '-l', foldername])
without needing to worry about whether or not foldername contains spaces.


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


Re: [Tutor] calling global in funtions.

2014-02-26 Thread eryksun
On Wed, Feb 26, 2014 at 8:45 AM, Steven D'Aprano  wrote:
>> :4: SyntaxWarning: name 'a' is assigned to before global declaration
>
> This is just a warning. It is STRONGLY RECOMMENDED that you put the
> global declaration at the top of the function, but it is not compulsary.
> If you put it somewhere else, you will get a warning, but the function
> will still work.

The declaration doesn't have to go at the top to avoid the warning. A
variable has to be declared global before it's used or assigned.
However, it's a good practice to put it at the top of the function
definition. This is for your own good, in case you accidentally try to
use a name as both local and global in the same function. All usage
will be global, which will probably be a bug.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Cameron,

Many thanks for your helpful comments. I do still have some problems
with my script, but it's probably better to start a new thread with an
appropriate subject.

I'm a bit new to Python, so it still seems like magic sometimes
(someone else said the same in a different thread). A lot of my coding
is 'trial & error', and I'll admit that at the moment my main goal is
getting things to work; after that I can explore making my code more
efficient/readable etc. But I appreciate your suggestions.

On 26/02/14 05:31, Cameron Simpson wrote:
> Hi Bob,
> 
[...]
> 
> The other things are just script remarks, not directly related to
> your problem:
> 
> On 24Feb2014 16:07, Bob Williams 
> wrote:
>> if pathList[j][-3:] == "mp3":
> 
> This is often written (I've inserted a dot, assuming you don't
> want "foomp3", only "foo.mp3"):
> 
> if pathList[j].endswith(".mp3"):
> 
> More readable, and also more reliable because it doesn't rely on 
> you getting the "3" correct.
> 
Yes, and reduces the need for explanatory comments.

>> linkName1 = pathList[j][0:-3] + "mp3"
> 
> Isn't this exactly the same as pathList[j] ?
> 
Actually, no. pathList[j] can contain either .mp3 files or .flac
files. In fact the main function of the script is to run all the flacs
through lame to convert them into mp3s. If they are already mp3s, then
a symlink will suffice.

>> linkName2 = destPath + linkName1[len(sourcePath):]
> 
> You might want to spell this:
> 
> linkName2 = os.path.join(destPath, linkName1[len(sourcePath):])
> 
More good stuff. :-)

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMOC0UACgkQ0Sr7eZJrmU77fwCeIAgFpOKEdt5C6Q/qzHPQglnm
91gAnRLHLs5u/369RNsBOMOFeZVhTiN5
=w7La
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Editing values from a dictionary

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi List,

I have two problems, but it's possible that one solution will suffice.
I am using a module called mutagen to extract audio metadata from
.flac files. The output of mutagen is in the form of a dictionary, so

In [1]: import mutagen.flac

In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The
Incredible String Band/1967 The 5000 Spirits Or The Layers Of The
Onion/08 The Hedgehog's Song.flac")

In [3]: print metadata["artist"]
[u'The Incredible String Band']

I now want to pass that string to another program, but I want to strip
off the leading [u' and the trailing ']. However, this doesn't work:

In [4]: artistName = metadata["artist"][3:-2]

In [5]: print artistName
[]

I was expecting The Incredible String Band, not []

What am I doing wrong? Or what have I misunderstood?

The other problem concerns the program that receives these arguments -
it complains (and stops with an error) if one the arguments is empty.
For example, the flac file may not have the date information:

Traceback (most recent call last):
  File "/home/bob/Documents/scripts/python/flac2mp3v2.py", line 81, in
 subprocess.call(['lame', '--add-id3v2',
'--ignore-tag-errors', '--tt', str(metadata['title']), '--ta',
str(metadata['artist']), '--tl', str(metadata['album']), '--ty',
str(metadata['date']), '--tn', str(metadata['tracknumber']), '--tg',
str(metadata['genre']), tempName1, tempName3])
  File "/usr/lib/python2.7/site-packages/mutagen/__init__.py", line
85, in __getitem__
else: return self.tags[key]
  File "/usr/lib/python2.7/site-packages/mutagen/_vorbis.py", line
184, in __getitem__
if not values: raise KeyError, key
KeyError: 'date'

If it's possible to edit the string value that gets passed to
subprocess.call('lame'...) - see problem #1 above, would it also be
possible to define a default value if the original field is empty?

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMOH9sACgkQ0Sr7eZJrmU5ufACeILRlmiXt4CgDa6ZpdTI3Npm5
FToAn2+AcjNKGxJKU+9nE9IdsoEqlQdd
=JpdC
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Editing values from a dictionary

2014-02-26 Thread Ben Finney
Bob Williams  writes:

> In [3]: print metadata["artist"]
> [u'The Incredible String Band']
>
> I now want to pass that string to another program, but I want to strip
> off the leading [u' and the trailing '].

You may be assuming that ‘metadata["artist"]’ is a text string; I
suspect it is not.

Try ‘type(metadata["artist"])’, to get Python to tell you what the type
of that object is.

-- 
 \  “Those who write software only for pay should go hurt some |
  `\ other field.” —Erik Naggum, in _gnu.misc.discuss_ |
_o__)  |
Ben Finney

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


Re: [Tutor] Editing values from a dictionary

2014-02-26 Thread Krishnan Shankar
Hi Bob,

>>>
In [3]: print metadata["artist"]
[u'The Incredible String Band']
<<<

Here u' and ' is not something you can strip off as it is part of python
datatype called UNICODE. Python prints a word or sentence in double or
singles quotes when it is a STRING or UNICODE in interpreter. These are
python datatypes. And even if there are any whitespaces in your data,

For example:  a = [u'   The Incredible String Band   ']

Here there are leading and trailing spaces in the string which is inside
the LIST. Do a

a[0].strip()

Another thing above is that your string in inside a LIST so to access the
string to strip it, you need to specify the place value as i have done
above.

If you do the above you can get the string as you need it.

And if you dont need a 'u' in front of your string simply convert it to a
string with str() method like below.

>>> s = u'spam'
>>>
>>>
>>> s
u'spam'
>>> type(s)

>>> str(s)
'spam'
>>> type(str(s))

>>>

Regards,
Krishnan


On Wed, Feb 26, 2014 at 10:39 PM, Bob Williams
wrote:

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> Hi List,
>
> I have two problems, but it's possible that one solution will suffice.
> I am using a module called mutagen to extract audio metadata from
> .flac files. The output of mutagen is in the form of a dictionary, so
>
> In [1]: import mutagen.flac
>
> In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The
> Incredible String Band/1967 The 5000 Spirits Or The Layers Of The
> Onion/08 The Hedgehog's Song.flac")
>
> In [3]: print metadata["artist"]
> [u'The Incredible String Band']
>
> I now want to pass that string to another program, but I want to strip
> off the leading [u' and the trailing ']. However, this doesn't work:
>
> In [4]: artistName = metadata["artist"][3:-2]
>
> In [5]: print artistName
> []
>
> I was expecting The Incredible String Band, not []
>
> What am I doing wrong? Or what have I misunderstood?
>
> The other problem concerns the program that receives these arguments -
> it complains (and stops with an error) if one the arguments is empty.
> For example, the flac file may not have the date information:
>
> Traceback (most recent call last):
>   File "/home/bob/Documents/scripts/python/flac2mp3v2.py", line 81, in
>  subprocess.call(['lame', '--add-id3v2',
> '--ignore-tag-errors', '--tt', str(metadata['title']), '--ta',
> str(metadata['artist']), '--tl', str(metadata['album']), '--ty',
> str(metadata['date']), '--tn', str(metadata['tracknumber']), '--tg',
> str(metadata['genre']), tempName1, tempName3])
>   File "/usr/lib/python2.7/site-packages/mutagen/__init__.py", line
> 85, in __getitem__
> else: return self.tags[key]
>   File "/usr/lib/python2.7/site-packages/mutagen/_vorbis.py", line
> 184, in __getitem__
> if not values: raise KeyError, key
> KeyError: 'date'
>
> If it's possible to edit the string value that gets passed to
> subprocess.call('lame'...) - see problem #1 above, would it also be
> possible to define a default value if the original field is empty?
>
> Bob
> - --
> Bob Williams
> System:  Linux 3.11.10-7-desktop
> Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
> Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.22 (GNU/Linux)
> Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/
>
> iEYEARECAAYFAlMOH9sACgkQ0Sr7eZJrmU5ufACeILRlmiXt4CgDa6ZpdTI3Npm5
> FToAn2+AcjNKGxJKU+9nE9IdsoEqlQdd
> =JpdC
> -END PGP SIGNATURE-
> ___
> 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] Editing values from a dictionary

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 26/02/14 17:29, Ben Finney wrote:
> Bob Williams  writes:
> 
>> In [3]: print metadata["artist"] [u'The Incredible String Band']
>> 
>> I now want to pass that string to another program, but I want to
>> strip off the leading [u' and the trailing '].
> 
> You may be assuming that ‘metadata["artist"]’ is a text string; I 
> suspect it is not.
> 
> Try ‘type(metadata["artist"])’, to get Python to tell you what the
> type of that object is.
> 
Aha! Sounds of pennies dropping ;-)

In [7]: type(metadata["artist"])
Out[7]: list

In [12]: print metadata["artist"][0]
The Incredible String Band

Gets me what I want. Thank you.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMOKP8ACgkQ0Sr7eZJrmU5a0ACdEH9kJPtHmbQ9w8YXrUc3NJT1
/t8AnitS+J4+kcM2z+Ai6Ak7cbe7Qnmk
=Sv8P
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] calling global in funtions.

2014-02-26 Thread Santosh Kumar
Thank you all. I understood the global function now.


On Wed, Feb 26, 2014 at 7:42 PM, eryksun  wrote:

> On Wed, Feb 26, 2014 at 8:45 AM, Steven D'Aprano 
> wrote:
> >> :4: SyntaxWarning: name 'a' is assigned to before global
> declaration
> >
> > This is just a warning. It is STRONGLY RECOMMENDED that you put the
> > global declaration at the top of the function, but it is not compulsary.
> > If you put it somewhere else, you will get a warning, but the function
> > will still work.
>
> The declaration doesn't have to go at the top to avoid the warning. A
> variable has to be declared global before it's used or assigned.
> However, it's a good practice to put it at the top of the function
> definition. This is for your own good, in case you accidentally try to
> use a name as both local and global in the same function. All usage
> will be global, which will probably be a bug.
>



-- 
D. Santosh Kumar
RHCE | SCSA
+91-9703206361


Every task has a unpleasant side .. But you must focus on the end result
you are producing.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] viewkeys,viewvalues,viewitems : Use Cases

2014-02-26 Thread Santosh Kumar
I want to understand about where to use ,
viewkeys()
viewvalues()
viewitems()

Thanks,
santosh


On Wed, Feb 26, 2014 at 6:59 PM, Alan Gauld wrote:

> On 26/02/14 07:04, Santosh Kumar wrote:
>
>  I defined a dictionary a below.
>>
>> In [14]: a = {'a':1,'b':2,'c':3}
>> ...
>>
>> Funtion associated with dictionaries.
>>
>> In [11]: print a.viewkeys()
>> dict_keys(['a', 'c', 'b'])
>>
>> In [12]: print a.viewvalues()
>> dict_values([1, 3, 2])
>>
>> In [13]: print a.viewitems()
>> dict_items([('a', 1), ('c', 3), ('b', 2)])
>>
>> Where do i use these , can i get any user cases.
>>
>
> What is 'these'?
> Do you mean:
>
> 1) where do I use a dictionary?
> 2) where do I use viewXXX()?
> 3) How do viewXXX differ from XXX (eg a.viewkeys v a.keys)?
>
> I'm not sure which aspect you want help with?
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
D. Santosh Kumar
RHCE | SCSA
+91-9703206361


Every task has a unpleasant side .. But you must focus on the end result
you are producing.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] viewkeys,viewvalues,viewitems : Use Cases

2014-02-26 Thread Dave Angel
 Santosh Kumar  Wrote in message:
> 
want to understand about where to use ,
viewkeys()
viewvalues()
viewitems()

..

Sometimes you want to loop through a dict,  doing something with
 each of the items.  For example you want to generate a report.
 

Suppose you have a dict where the keys are names and the values
 are grades. Perhaps you want to calculate the average grade.  You
 don't care about names,  so you loop through values.

Or you want to check how many names begin with J. Loop through the
 keys. 



-- 
DaveA

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


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Dave Angel
 Bob Williams  Wrote in message:

> 
>>> linkName1 = pathList[j][0:-3] + "mp3"
>> 
>> Isn't this exactly the same as pathList[j] ?
>> 
> Actually, no. pathList[j] can contain either .mp3 files or .flac
> files. In fact the main function of the script is to run all the flacs
> through lame to convert them into mp3s. If they are already mp3s, then
> a symlink will suffice.
> 
>>> 

If you're dealing with more than one extension,  and especially if
 they're different lengths,  consider using splitext
-- 
DaveA

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


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 26/02/14 15:41, Bob Williams wrote:
On 26/02/14 05:31, Cameron Simpson wrote:
>>> linkName1 = pathList[j][0:-3] + "mp3"
>>> 
>>> Isn't this exactly the same as pathList[j] ?
>>> 
> Actually, no.

Actually, you are right. I've trimmed down that block now, thank you.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  18:00pm up 3:41, 5 users, load average: 2.73, 2.45, 1.92
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMObU0ACgkQ0Sr7eZJrmU5AhgCgpolM3vDLEDzEy8t1o4O+5zCA
B58AoJJC3IeyXqt3onBNnoaUaW833Lj3
=BhVn
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Cameron Simpson
On 26Feb2014 15:41, Bob Williams  wrote:
> Many thanks for your helpful comments. I do still have some problems
> with my script, but it's probably better to start a new thread with an
> appropriate subject.

Very true.

> I'm a bit new to Python, so it still seems like magic sometimes
> (someone else said the same in a different thread). A lot of my coding
> is 'trial & error', and I'll admit that at the moment my main goal is
> getting things to work; after that I can explore making my code more
> efficient/readable etc. But I appreciate your suggestions.

Readable helps. Even for the author (when you come back later,
not to mention when trying to explain the code to others).

> >> linkName1 = pathList[j][0:-3] + "mp3"
> > 
> > Isn't this exactly the same as pathList[j] ?
> > 
> Actually, no. pathList[j] can contain either .mp3 files or .flac
> files.

Except that I thought this was inside the if-statement, so you know that this
time it is an mp3.

Cheers,
-- 
Cameron Simpson 

Trust the computer industry to shorten Year 2000 to Y2K. It was this
thinking that caused the problem in the first place.
- Mark Ovens 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Editing values from a dictionary

2014-02-26 Thread Steven D'Aprano
On Wed, Feb 26, 2014 at 05:09:49PM +, Bob Williams wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
> 
> Hi List,
> 
> I have two problems, but it's possible that one solution will suffice.
> I am using a module called mutagen to extract audio metadata from
> .flac files. The output of mutagen is in the form of a dictionary, so
> 
> In [1]: import mutagen.flac
> 
> In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The
> Incredible String Band/1967 The 5000 Spirits Or The Layers Of The
> Onion/08 The Hedgehog's Song.flac")
> 
> In [3]: print metadata["artist"]
> [u'The Incredible String Band']

Get rid of the print, which automatically converts whatever you pass it 
to strings and then displays those strings. If you inspect the item 
directly, you will see that the value you have is not a string:

"[u'The Incredible String Band']"


but a list [ ... ] containing one item, which is a string.

Since you are using an interactive shell, in this case ipython, you can 
drop the call to print, and just enter metadata["artist"] on its own, 
and you'll see *exactly the same output*, without quotation marks on the 
outside. That tells you that what you have is not a string.

(If it were a string, you would see quote marks surrounding it.)

If you're still not convinced, call:

type(metadata['artist'])

and take note of what it says.

Once you have convinced yourself that it is in fact a list of one item, 
you can extract that item like this:

item = metadata['artist'][0]

but beware! The fact that mutagen returns a list rather than the string 
directly warns you that sometimes there might be two or more pieces of 
metadata with the same key, e.g.:

# some imaginary metadata from a hypothetical FLAC file
[u'The Beatles', u'The Rolling Stones', u'ABBA']

So you need to be prepared to deal with multiple metadata items.

One last thing: you *do not* want to get rid of the leading u, trust me 
on this. The u is not actually part of the string itself, it is just a 
delimiter. What you are seeing is the difference between a Unicode text 
string and a byte-string.

A regular string with "" or '' delimiters consists of a sequence of 
bytes. Bytes, as you probably are aware, are numbers between 0 and 255 
inclusive. But you don't enter them using their numeric value, but by 
their character value. Python gives you two functions for converting 
between the numeric and character values:

chr(n)  # returns the character of ordinal n
ord(c)  # returns the ordinal of character c

and uses ASCII for the first 127 ordinal values, and some arbitary and 
likely unpredicatable scheme for the rest.

Byte strings have their uses, but for text, it's not 1960 any longer, 
and there is an entire world filled with people for whom ASCII is not 
enough. (In truth, *even in America*, the ASCII character set was never 
sufficient for all common uses, since it lacks symbols such as ¢.) In 
the 1980s and 90s the world proliferated a confusing mess of dozens of 
alternative character sets, often called "extended ASCII" as if there 
were only one, but fortunately it is now 2014 and the right solution is 
to use Unicode.

Unlike byte-strings, which only contain 256 possible characters, Unicode 
strings can contain over a million distinct characters, numbered between 
U+ and U+10 (the number after the U+ is in hexadecimal). It 
contains a dedicated character (technically called a "code point") for 
each and every character included in all of those dozens of legacy 
so-called "extended ASCIIs", plus many more that they never included.

Unicode strings use delimiters u"" and u'', so as you can see the u is 
*outside* the quote marks, it is part of the delimiter, not part of the 
string. Unicode strings allow metadata to include artist's who have 
non-ASCII characters in their names, like Sinéad O'Connor and Björk, as 
well as stylistic "heavy metal umlauts" as used by artists like William 
Ørbit and Blue Öyster Cult. And even totally pretentious wankfests like 
▼□■□■□■, and no I have no idea how that's pronounced.

(Alas, the Love Symbol in The Artist Formerly Known As Love Symbol is 
not available in Unicode, so he'll have to be known as The Artist 
Formerly Known As The Artist Formerly Known As Prince.)

So you should prefer Unicode strings over byte-strings. Apart from the 
leading u prefix, there is practically no difference in how you use 
them. All the usual string methods are available:

py> print(u'Björk'.upper())
BJÖRK

Just be careful about mixing regular '' byte strings and proper u'' 
Unicode text strings. Python 2 tries to do the "smart" thing when you 
combine them, and while that works 9 times out of 10, the tenth time you 
end up even more confused than ever. (Python 3 is far more strict about 
keeping them separate.)


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

[Tutor] OT: supporting Python & the PSF with a half/quarter-page ad?

2014-02-26 Thread wesley chun
Hey everyone,

This is somewhat off-topic for this list, but if you've gotten a lot out of
Python and want to contribute, the Python Software Foundation is advocating
for the language by creating and distributing a
brochurethat talks all about the
goodness of Python. For the first run, they're
making "10,000 copies which the PSF will then distribute to user groups,
Python conferences and educational institutions on request and free of
charge."

If your company is interested in supporting the project and want to
advertise in it but find the half-page ad cost prohibitive at EURO 2650
(~$3636) or the 3-line reference ad listing at EURO 500 (~$686) too small, let
me know. I'm willing to split the cost of the ad (creating 2 quarter-page
ads).. the PSF organizer of the brochure suggested this as an alternative,
so now I want to see if any of you or your companies want to participate.
The full details can be found here
.

The deadline is this Fri, Feb 28, so please get back to me by tomorrow
privately... thanks!
-- Wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
+wesley chun  : wescpy at gmail :
@wescpy
Python training & consulting : http://CyberwebConsulting.com
"Core Python" books : http://CorePython.com
Python blog: http://wescpy.blogspot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor