-1

I have two python files located in different directories.

folder1
    |--> routing.py
folder2
    |--> script.py

I want to execute script.py from routing.py. script.py takes multiple parameters to run. Currently, I am using subprocess module python.

routing.py

import os
import subprocess
import sys

def test():
    dirpath = os.getcwd()
    os.chdir(folder2_path)
    output = subprocess.check_output([sys.executable, "script.py", param1, param2, param3 ])

but, I am getting

raise CalledProcessError(retcode, cmd, output=output)

Is there any better way to do this? Do I miss something?

Matze
  • 5,100
  • 6
  • 46
  • 69
Bhimasen
  • 677
  • 3
  • 8
  • 19
  • In general you need not `chdir` to the directory (this means influencing your own process more than you typically want) because you can simply give the working directory to the call of `check_output()`. – Alfe Oct 08 '18 at 11:20
  • Can you re-work your `script.py` file so that you import it and call the function you want to run? – toti08 Oct 08 '18 at 11:23
  • `check_output` is *supposed* to throw an error if the subprocess fails. You want to avoid calling Python as a subprocess of Python anyway. See further https://stackoverflow.com/a/51950538/874188 – tripleee Oct 08 '18 at 11:28

3 Answers3

1

It works for me

python1.py

import sys
global var
arg1 = sys.argv[1]
arg2 = sys.argv[2]

var = int(arg1) + int(arg2)
print var

and the next file is

import os
import subprocess
import sys

def test():
    dirpath = os.getcwd()
    os.chdir('.')
    output = subprocess.check_output([sys.executable, "python1.py", '3', '3' ])
    print "output: ",output

test()
Anand Thati
  • 173
  • 1
  • 1
  • 9
1

There are multiple problems with your code here. Here is a hopefully minimal fix:

import os
import subprocess
import sys

def test():
    return subprocess.check_output([
        os.path.join(['folder1', sys.executable], 
        os.path.join(['folder2', "script.py"],
        param1, param2, param3 ])

A much better solution is to refactor script.py so that you can import it from your current script. This is also brittle in the sense that it requires the current directory to be the directory of the current script.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

You're trying to call the script from a different folder. Try with ../folder2/script.py as an argument to check_output, or, if the other script contains relative/non-absolute paths too, consider rewriting it so that you can import methods and classes from it instead of trying to execute it externally.

msaba92
  • 357
  • 2
  • 10