0

I am attempting to run a python script located in a folder on my server from another python script. The location of the script I am attempting to run is not in the same location as the existing script. The script I am trying to execute is not a function I just need it to start once the first one has completed, and I know they both work independently of each other. I have found a similar post but I get the error Not Found when I use either os.system or subprocess.Popen.

I know that the directory I am calling is correct because in the previous statement I call a shutil.move to move a file to the same directory the scipt I would like to run is in.

This is what I have tried:

subprocess.Popen("/home/xxx/xxxx/xxx/xx/test.py")

os.system("/home/xxx/xxxx/xxx/xx/test.py")

subprocess.Popen("/home/xxx/xxxx/xxx/xx/test.py", shell=True)
Community
  • 1
  • 1
risail
  • 509
  • 5
  • 14
  • 37

3 Answers3

0

For a script that does operations related to its location, you will want to first get the current directory you are in using originalDir = os.path.dirname(full_path). Next you will want to use os.chdir('/home/xxx/xxxx/xxx/xx/') and then do a subprocess.Popen("python test.py", shell=True) to run the script. Then do an os.chdir(originalDir) to get back to the directory you once were in.

heinst
  • 8,520
  • 7
  • 41
  • 77
0

You could try something like this:

original_dir = os.getcwd()
script_paths = ["/...path1.../script1.py", "/...path2.../script2.py", "/...path3.../script3.py"]

for script_path in script_paths:
  base_path, script = os.path.split(script_path)
  os.chdir(original_dir)
  subprocess.Popen(script)


os.chdir(original_dir)
will
  • 10,260
  • 6
  • 46
  • 69
0

To run a script as a subprocess in its directory, use cwd parameter:

#!/usr/bin/env python
import os
import sys
from subprocess import check_call

script_path = "/home/xxx/xxxx/xxx/xx/test.py"
check_call([sys.executable or 'python', script_path],
           cwd=os.path.dirname(script_path))

The difference from os.chdir()-based solution is that chdir() is called only in the child process. The parent working directory stays the same.

sys.executable is a python executable that executes the parent Python script. If test.py have a correct shebang set and the file has executable permissions then you could run it directly (use [script_path] without shell=True).

jfs
  • 399,953
  • 195
  • 994
  • 1,670