this might be a dumb question, but what’s the “rig...
# general
h
this might be a dumb question, but what’s the “right” way to write a file into the same directory as your repo when running a script through a
pex_binary
? using
__file__
as a starting point doesn’t work since all the files are running in pants’ temp directory
h
Not at all dumb. Imo it's confusing, and I still get confused by it! This is relevant https://github.com/pantsbuild/pants/issues/12129 For Pants's own scripts, we simply use a relative path from the build root and it Just Works. Like
Path("dir/write_me.txt")
h
hmm, so something like this should work?
Copy code
with open(Path("src/path/to/whatever.json"), "w") as f_:
    json.dump(data, f_)
what if i didn’t know beforehand where the output would be, or wanted to write something relative to the file where a function is being called?
Path(__file__).absolute()
unfortunately returns the file from the pantsdir and not the actual repo
h
yes that is right. Re dynamic, cc @bitter-ability-32190 who has been looking into this - do you know how?
h
the best I’ve come up with is this:
Copy code
Path().joinpath("src", *__package__.split("."), "file.ext").absolute()
which works but feels weird and not at all like the right way to do things 😛 (and it also requires hardcoding in the
src/
directory)
b
You basically got it. We don't use source roots, so we don't worry about
src
. Admittedly not great
🤔 1
h
Hm not great indeed. I wonder how we fix this. Probably https://github.com/pantsbuild/pants/issues/12129
b
Actually I wonder if we could do this a different way. What if we didn't source-root-strip in the sandbox for
run
, but set the right PYTHONPATH?
Ehh, probably wouldnt work right, still. Just another indirection
h
b
Yeah, if you have a source root, I think theres no way to fall into the pit of success on this one 😕