thebjorn
thebjorn

Reputation: 27321

tempfile.mkdtemp() difference on osx?

The following unit test passes on all linux/python and windows/python combinations:

import os
import tempfile
from contextlib import contextmanager

def test_cd_to_tempdir():
    initial_cwd = os.getcwd()
    abspath_tmpdir = tempfile.mkdtemp()
    try:
        assert os.path.isabs(abspath_tmpdir)
        os.chdir(abspath_tmpdir)
        curdir = os.getcwd()
        assert initial_cwd != curdir
        assert curdir == abspath_tmpdir
    finally:
        os.chdir(initial_cwd)      # must exit directory..
        os.rmdir(abspath_tmpdir)   # ..before it can be removed

and fails on osx (only tested 3.7.4) with the following failure:

        try:
            assert os.path.isabs(abspath_tmpdir)
            os.chdir(abspath_tmpdir)
            curdir = os.getcwd()
            assert initial_cwd != curdir
>           assert curdir == abspath_tmpdir
E           AssertionError: assert '/private/var...T/tmpoz7eo_yj' == '/var/folders/...T/tmpoz7eo_yj'
E             - /private/var/folders/17/5mc7816d3mndxjqgplq6057w0000gn/T/tmpoz7eo_yj
E             ? --------
E             + /var/folders/17/5mc7816d3mndxjqgplq6057w0000gn/T/tmpoz7eo_yj

I'm not a mac person, so I don't really know how the /private/ prefix works (some googling makes me believe it is the mac equivalent of the windows %APPDATA%).

Is there a way to write this code in a cross-platform way?

(the travis run is at https://travis-ci.org/datakortet/yamldirs/jobs/607842061 if anyone is interested).

Upvotes: 4

Views: 2171

Answers (3)

Zane Dufour
Zane Dufour

Reputation: 911

If you're working with pathlib.Paths, the equivalent method would be .resolve(), e.g.:

assert Path(curdir).resolve() == Path(abspath_tmpdir).resolve()

Upvotes: 1

dB.
dB.

Reputation: 4770

The /tmp location is a symlink to /private/tmp.

path = tempfile.TemporaryDirectory()
path.name: /var/folders/lf/872sgt9n4ld5s20mdj0_5txrds0wb5/T/tmpbxdp5c99
subprocess.check_output("pwd").decode().strip(): /private/var/folders/lf/872sgt9n4ld5s20mdj0_5txrds0wb5/T/tmpbxdp5c99
os.getcwd(): /private/var/folders/lf/872sgt9n4ld5s20mdj0_5txrds0wb5/T/tmpbxdp5c99
os.path.realpath(path.name): /private/var/folders/lf/872sgt9n4ld5s20mdj0_5txrds0wb5/T/tmpbxdp5c99

Upvotes: 0

wim
wim

Reputation: 362776

/tmp is a symlink to /private/tmp on macOS (and same goes for /var). See cross-site Q&A Why is /tmp a symlink to /private/tmp?

So to write it cross-platform, you could just resolve links:

assert os.path.realpath(curdir) == os.path.realpath(abspath_tmpdir)

Upvotes: 4

Related Questions