1

I made a script in Python 3.9.2 that uses pathlib (pathlib.Path.cwd()) to get current script's folder (I then made an .exe file using PyInstaller)

If i start the script/exe manually no worries, but if I use windows scheduler or i start the script /.exe without beeing in the current folder, pathlib.Path.cwd() (correctly) gets the current folder where I am, not the script's folder

e.g. in windows terminal

cd [...]\folderWithMyScript
py myScript.py

works good but if I'm in my home directory C:\Users\myName and I start the script from there

py [pathToTheScript]

It wont' work (since he can't find some other folder which are below the script folder, the whole script uses a lot .joinpath('something')

Thank you in advance!

Dife
  • 11
  • 1
  • 3
  • Have you tried some of the suggestion in the docs? https://pyinstaller.readthedocs.io/en/stable/runtime-information.html – Ralf Mar 26 '21 at 10:59
  • @Ralf No, but now i'll look into it, thank you Although the problem is in the python script, a .exe made with pyinstaller and started with windows scheduler is just my final objective, but as i said the problem persist even if i launch the script.py straight up with python. – Dife Mar 26 '21 at 11:02
  • Does this answer your question? [How do you properly determine the current script directory?](https://stackoverflow.com/questions/3718657/how-do-you-properly-determine-the-current-script-directory) – Andrew Marshall Mar 26 '21 at 11:12
  • @AndrewMarshall this is like the answer i got in this thread, I will try it but i honestly wanted to use only pathlib and ignore the `os` lib – Dife Mar 26 '21 at 11:22
  • pathlib uses os anyway, so importing that shouldn't be a problem – cbolwerk Mar 27 '21 at 15:43

5 Answers5

1

VersBersch's answer should be the correct answer.

Path(__file__).resolve(strict=True).parent[]
0

pathlib.Path.cwd() will not give you your script's folder, it is to get the current work directory. A.k.a where you run the command to run the script. The correct way to get your script's folder is: os.path.dirname(os.path.realpath(__file__))

see How can I find script's directory?

Cheukting
  • 264
  • 1
  • 6
0

So, in the end i gave up and used os lib

I did somethin like this (so i could still use the pathlib in the whole script)

trueDir = pathlib.Path(os.path.dirname(os.path.realpath(__file__)))

Thank you for all your kind answers !

Dife
  • 11
  • 1
  • 3
0

Something important I just found out is, that you might run into troubles using __file__ if you're going to convert youre program into an executable file. Instead you should use sys.executable. Took me a while to find out... source

0
file_path = os.path.dirname(sys.executable)

for get the path directory of .exe

Malou
  • 141
  • 8