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).
/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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With