Comment 10 for bug 366353

Revision history for this message
Jörgen Stenarson (jorgen-stenarson) wrote : Re: [Bug 366353] Re: %run doesn't work with paths returned by tempfile.NamedTemporaryFile()

Brian Granger skrev:
> Here is the actual error and the path names that seem to be problematic:
>
> In [1]: import tempfile
>
> In [2]: f = tempfile.NamedTemporaryFile()
>
> In [3]: f.name
> Out[3]: 'c:\\docume~1\\admini~1\\locals~1\\temp\\tmpfydqw_'
>
> In [4]: f.write('pass\n')
>
> In [5]: %run $f.name
> ERROR: File `c:docume~1admini~1locals~1temptmpfydqw_.py` not found.
>

Perhaps you can use something like this to get the full pathname first.

The code below was based on a function from
<https://svn.participatoryculture.org/svn/dtv/tags/Democracy-Player-0.9.1.1/tv/platform/windows-xul/platformutils.py>

import ctypes
_GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
_GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
ctypes.c_uint ]

def get_long_path_name(path):
     buf = ctypes.create_unicode_buffer(260)
     rv = _GetLongPathName(path, buf, 260)
     if rv == 0 or rv > 260:
         return path
     else:
         return buf.value

or using win32api (which is not a standard library but comes with pywin32)

import win32api
win32api.GetShortPathName (path_name)

I would probably choose the first approach because ctypes is a
dependency of pyreadline which most users of ipython would have anyway.
But pywin32 is not.

using either of these solutions you can do

In [7]: import win32api, tempfile

In [8]: f = tempfile.NamedTemporaryFile()

In [9]: f.name
Out[9]: 'c:\\docume~1\\jstenar\\lokala~1\\temp\\tmp3xrtkk'

In [10]: win32api.GetLongPathName(f.name)
Out[10]: 'c:\\Documents and Settings\\jstenar\\Lokala
inst\xe4llningar\\Temp\\tmp3xrtkk'

In [11]: get_long_path_name(f.name)
Out[11]: u'c:\\Documents and Settings\\jstenar\\Lokala
Inst\xe4llningar\\Temp\\tmp3xrtkk'

In [12]: win32api.GetLongPathNameW(f.name)
Out[12]: u'c:\\Documents and Settings\\jstenar\\Lokala
inst\xe4llningar\\Temp\\tmp3xrtkk'