[python-win32] raw string

Tim Roberts timr at probo.com
Fri Aug 20 18:59:04 CEST 2004


On Thu, 19 Aug 2004 19:19:58 +0530, Anand K Rayudu 
<anand.k.rayudu at esi-group.com> wrote:

>Hi all,
> 
>i have com interface which  returns a string. in my case it is returning  
>"E:\data\models\neonmodel.dat"
>if i print the value \n is interpted as new line charcter and if  i use os.access(file,os.R_OK) it returns false.
>  
>

Are you SURE the \n is being interpreted as a newline, or are you 
GUESSING that because os.access fails?

>How can i specify not to consider the string in raw mode
>
>in static string i would have used it as r"E:\data\modes\neonmodel.dat"
>but if i have that already as variable, how can i do it
>  
>

The intepretation of \n and other escape characters is only done when 
the interpreter reads literal strings in your program source code.  
Backslash intepretation is not done on string variables.  Consider this:

   myString1 = "e:\n"   # this variable contains 3 characters
   myString2 = "e:\\n"  # this variable contains 4 characters
   myString3 = r"e:\n"  # this variable contains 4 characters

myString1 contains a newline.  The other two do not.  Once it is in that 
form, they will not be re-examined for backslashes.  Now, if you print 
myString2 or myString3 in the interpreter, it will look like 5 
characters  ('e:\\n'), but that's just a side effect of the 
interpreter.  The strings contain 4, and they will contain 4 no matter 
where you send it.

If your program receives a string with those 4 characters, it will never 
be misinterpreted as containing a newline.

Now, if this string is coming to you from a C object, it's possible that 
the object's code is doing the wrong thing.  For example, consider this 
C code with a common error:

    STDMETHODIMP HRESULT
    GiveMeAString( LPSTR psz )
    {
        strcpy( psz, "e:\data\models\neomodel.dat";
        return S_OK;
    }

This code will return to you a string that contains a newline.   The 
string does NOT contain the two characters "backslash n" that later need 
to be convered into a newline.  If you get this string in a Python 
program, you will have a string with a newline.  The correct way to do 
this in C is:

    STDMETHODIMP HRESULT
    GiveMeAString( LPSTR psz )
    {
        strcpy( psz, "e:\\data\\models\\neomodel.dat";
        return S_OK;
    }

>my python code looks like this
>
>from win32com.client import Dispatch
>
>aa=Dispatch("MyExecutive.MyAPIs")
>file=aa.getFileName()
>import os
>#file=r"E:\data\models\model.dat" // if i uncomment it is ok
>if(os.access(file,os.R_OK)==True): // access files as it is not in raw
>   aa.readFile(file)
>  
>

There is nothing wrong with this code.  The bug must be in the 
MyExecutive object.

-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-win32 mailing list