SaiVamshi Dobbali SaiVamshi Dobbali - 3 months ago 7
Python Question

Running Python script through subprocess fails

I am trying to run util.py from script

file1.py
using
subprocess
. Both of them are in same directory. When I run them from current directory it works fine, but if I run
file1.py
from different directory it fails.

file1.py:

#!/usr/bin/env python
import subprocess
out=subprocess.Popen(["./util.py"],shell=True)
print "done"


util.py:

#!/usr/bin/env python
def display():
print "displaying"
display()


error:

/bin/sh: ./util.py: No such file or directory
done

Answer

Executing ./util.py in a terminal means "Look in the current working directory for a file named util.py and run it." The working directory is the directory from where you run the command. This means that your python script cannot see util.py if you run it from a different directory.

If you are sure that file1.py and util.py always lie in the same directory, you could use __file__ and os.path.dirname to prefix it with the directory of file1.py:

file1.py:

#!/usr/bin/env python
import os
import subprocess

current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, "util.py")
out = subprocess.Popen([filename], shell=True)
print("done")
Comments