[Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?

Steven D'Aprano steve at pearwood.info
Sun Jan 7 03:05:59 EST 2018


On Sun, Jan 07, 2018 at 12:49:59AM -0600, boB Stepp wrote:

> Win7, Python 3.6.2
> 
> If I run a unit test with the following embedded:
> 
> print('realpath =', os.path.realpath('test_main.py'))
> 
> I get the following in my test output (Only relevant line is shown):
> 
> Ensure expected list of string integers is returned. ... 
> realpath = c:\Projects\solitaire_scorekeeper\test_main.py


realpath() returns the canonical path of the given filename. It doesn't 
try to locate some actual existing file. The fact that there is a file 
called "test_main.py" located here:

> In actuality "test_main.py" is located at
> "c:\Projects\solitaire_scorekeeper\tests\test_main.py"

is irrelevent. You asked for the "real" (canonical) path name to the 
relative pathname "test_main.py". That means in the current directory, 
which apparently is C:\Projects\solitaire_scorekeeper. Hence you get the 
result C:\Projects\solitaire_scorekeeper\test_main.py even though the 
"real file" is one directory further in.


> If I open the interpreter from the directory
> "c:\Projects\solitaire_scorekeeper\tests\" I get what I expect:

Indeed, because now the current directory is different.

I think you may be confused because you think realpath() has something 
to do with actual existing files. It doesn't. Remember that realpath() 
isn't just called on existing files, it may be called on arbitrary file 
names which don't exist. Its more like os.path.abspath() except that if 
the path contains symbolic links (not likely on Windows, but possible) 
they will be resolved to their real path.


-- 
Steve


More information about the Tutor mailing list