When opening files using a python script that references a relative link to a file, the program crashes and cannot find the file despite it falling under the same directory as the local script. Outside Komodo Edit, this works perfectly and a terminal call of the python file will get the correct input.
Does the working directory change when running a python script inside Komodo as opposed to manually executing it using terminal, and if so, is there a fix? I kind of like having to only use a command shortcut to run my scripts.
Could you please provide a test case on which we can reproduce the issue?
If you want to know in what path context your script is running use
print(os.getcwd()) #get the current working directory
The CWD can change constantly depending on what you’re doing, eg. currently active file directory, currently open project base dir, etc. I believe it defaults to the former.
Also, adding on what @nathanr said, providing the error you get would help us out. Pystderr.log in your Komodo user profile after a crash might give us some useful information.
A screenshot of the code, the files, and the output is below.
The sh terminal is the terminal that is used by komodo and usually runs quite fine (I have it linked with a run command with the option “create new terminal” ~ or something like that). The gnome terminal, the one with the green text, is my own where I 'cd’d to the directory and executed the file myself, which displayed the correct output. The zero means there is nothing in the text file, which there isn’t.
As careyh suggested, I also tested the getcwd function which worked but showed that the python file is using my linux home directory for the execution. The komodo log displayed nothing relevant to the error I’m getting which occurs within python.
So the problem is the directory being different, I suppose. Is it bad practice to just assume that the code being executed can use relative links to files? I haven’t had much experience developing commercial applications so I don’t know if I should be somehow hardcoding links to files (wouldn’t this muck up when executing on different platforms though?). Any thoughts would be appreciated, after all, it might not be a bug.
Turned out to be the solution to my problem, the python script works perfectly now.
I’m honestly not quite sure why this isn’t the default option though.
If anyone knows what the proper practice in python regarding file directory structures and relative file links etc I would still really like to hear as I haven’t come across anything mentioning it in books or tutorials.
I think there’s a case to be made both ways; depending on your script to be executed from the CWD is error prone.
Glad you got it sorted, thanks for letting us know