Same directory a couple of times removed doesn't seem to work.Here is what I useCode:
import syssys.path.append('/mnt/pi_lib/common')
Better to use something like the following than use a fixed path:Code:
import osimport syssys.path.append(os.path.dirname(os.path.abspath(__file__)))
By doing the above as long as the all the files are in the same directory it doesn't matter where that directory is.
Well, no, it wouldn't. When I wrote "all the files are in the same directory" "all" includes main.py as well as your custom modules. Though in hindsight if that were teh case you wouldn't need to modify python path.
I appologise if I was unclear.
In the past when developing using a main program and some custom imported modules I tend to keep everything in the same directory (or a sub directory configured as a python module). There a couple of advantages to that: it's much simpler to deploy the finished program and it keeps the main program and modules in sync - If later make a change to those shared modules you could end up breaking something that your older code relies on.
I do this even when the modules are shared between projects.
Keeping your code in sync with the modules and the version of those modules it reques without impacting other programs that need different version of the same modules is a large part of why python now defaults to wanting virtual environments before ti lets you use pip.
Going back to how to organise your code, it's good practice to keep delevopment versions and deployed/live versions separate. Doing so means you can change the dev version without introducing problems into the live one. Only when you've frozen and tested the dev version should you move it to live.
it probably doesn't matter much for small or infrequently used programs but for larger programs and/or programs run regularly (e.g under cron) you could find that because you're running the dev version your regular job has been failing without you realising.
The trouble with fixed paths in your code is that when they change, you have to change your code
Statistics: Posted by thagrol — Fri May 10, 2024 11:36 pm