Search code examples
python-3.xsubprocess

Run python script using another python interpreter through the subuprocess module?


Say I have a simple Hello_World.py script that will write a text file saying hello world.

import csv,sys

def main(fname):
    with open(fname, 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['Hello World'])

if __name__ == '__main__':
    fname = sys.argv[1]
    main(fname)

I can execute this from the command prompt for a specific python environment using

C:\Users\user\Anaconda3\envs\test\python.exe D:\Scripts\hello_world.py D:\Data\test.txt

However, how can i execute the same line of code from within another python version using for example the subprocess module? i.e. the following returns a non-zero exit status 1.

subprocess.check_call([r'C:\Users\user\Anaconda3\envs\test\python.exe',r'D:\Scripts\hello_world.py', r'D:\Data\test.txt'])

Definately not the most elegant approach but I unfortunately require the script to be run on a different python version. It would appear that there is some sort of error in calling python.exe considering that this will also fail

os.system(r'C:\Users\user\Anaconda3\envs\test\python.exe')

Solution

  • The issue has been resolved. I did not have permission access to the specified C folder. Why the subprocess.CalledProcessError function did not throw a permissionerror, I do not know.