[Tutor] Running python files

Mats Wichmann mats at wichmann.us
Tue Oct 13 19:59:12 EDT 2020


On 10/13/20 5:28 PM, Phil wrote:
> This seemingly simple problem has me scratching my head. How do I run a
> python file from a directory other than the directory that the python
> file is in? It's a little more complex than my question implies.
> 
> For example, "python3 ~/somedirectory/somefile.py" runs without a
> problem. However if somefile.py requires resources such as .png files
> then somefile.py won't run because those resources cannot be found.
> These resources are also stored in /somedirectory. The same somefile.py
> does run if stated from somedirectory.
> 
> Adding somedirectory to my user path didn't help and I've experimented
> with Python_Path but that's not the answer either.
> 
> I'm trying to run somefile.py from the system menu.
> 

It's a question of context.  Which so many things in computing are :)

A python process has a concept of a current working directory, that's
the one that is used when looking up relative paths.  "foo.png" is a
relative path - it's expected to be relative to the current directory.
The directory you start from is current, not the directory of the
script. When you put something in a menu, or in a cron job, those don't
have the same context as the directory you might be working in when you
type a shell command, so there's a good bit to think about here. There's
a way to find the script's directory (well, maybe not just one way)...

try this:

put a script somewhere that contains

import sys
print(sys.path[0])

and run that script from some other place.

Does this give you some ideas?




More information about the Tutor mailing list