Raw Strings (I Think)

Fredrik Lundh fredrik at pythonware.com
Wed Jul 23 16:25:11 EDT 2008


Lanny wrote:

> I've used glob.glob to get a list of files in a directory
> and now I want to use os.system to execute one of
> those files, the problem is that python automatically
> puts a escape charater infront of the back slashes
> so the os.system gets X:\\####\\####\\ and is useless,

No, it doesn't.  The backslash doubling only happens when you "echo" a 
variable to the terminal in interactive mode.  If you want to know that 
the string really contains, use "print".

Here's an example:

 >>> import glob
 >>> files = glob.glob("\\bin\\ls.exe")
 >>> files
['\\bin\\ls.exe']
 >>> files[0]
'\\bin\\ls.exe'
 >>> print files[0]
\bin\ls.exe
 >>> import os
 >>> os.system(files[0])
Demo                Makefile.pre.in     Parser
Doc                 Misc                Python
Grammar             Modules             README
Include             Objects             RISCOS
LICENSE             PC                  Tools
Lib                 PCbuild             configure
Mac                 PCbuild8            configure.in

Btw, if you want to pass arguments to the program, you might want to use 
the "subprocess" module instead, since it handles escaping and quoting 
for you all by itself:

 >>> import subprocess
 >>> subprocess.call([files[0], "-l"])
total 479
drwxr-xr-x  26 1006     everyone        0 Oct 14  2006 Demo
drwxr-xr-x  33 1006     everyone        0 Oct 14  2006 Doc
drwxr-xr-x   6 1006     everyone        0 Oct 14  2006 Grammar
...

There's also a function called "os.startfile", which can be used to 
"open" an arbitrary file (in the same as if you'd double-click on it in 
the explorer).

 > I think I need to convert my string to a raw string but
 > I don't know how.

Raw strings are an alternate syntax for adding string literals to your 
source code, and has nothing to do with output.

</F>




More information about the Python-list mailing list