0

I have a python script saved in a directory. When I run it from its folder it works as expected. However, when I run it through an interface (Unraid's User Script plug-in's "Run Script" button) it fails.

While troubleshooting I found that the command os.system("pwd") returns the script's directory when I run it from the directory, but \root when ran through the interface.

The script is failing as imported modules are looking for files in the directory the script is in.

I'm unable to change the modules, but is there a way to make the script think it is running in a specific directory regardless of where it is executed?

GFL
  • 1,278
  • 2
  • 15
  • 24
  • 1
    use `os.chdir()` – Nesi Jun 25 '23 at 14:10
  • In general, writing code that assumes it'll be run in a given working directory is a bug, and you should fix the code to no longer make that assumption. For example, you can generate paths relative to `__file__`, or update `sys.path` explicitly to change the search location used for `import`s – Charles Duffy Jun 25 '23 at 14:17
  • BTW, it's almost certainly `/root` not `\root` being returned: unraid is Linux-based, Linux uses forward slashes as path separators. – Charles Duffy Jun 25 '23 at 14:19
  • You should create a script to run the desired script for you : os.chdir(desired_directory) os.system('python your_script_that_needs_change_dir.py') – Mohsen Robatjazi Jun 25 '23 at 14:19

1 Answers1

0

To change the directory from within the script, make a call to chdir function from the os module. That is, add the following to the header of your script, before importing any modules,

import os
os.chdir('<path/to/modules>')

where <path/to/modules> must be replaced by the actual path to the modules you want to load.

Preferrably, if your problem is just a matter of importing modules from the directory the script is living in, you can append the path using the sys module. That is,

import sys
sys.path.append('<path/to/modules>')
lbarbele
  • 26
  • 1
  • 1