0

I been trying to run the ksh script from python using subprocess and need some help as environment variable are not being resolved which are being used inside the script. Any advice on proper way to export the path for subprocess to pick.

Tried to echo the path but it return same value with being resolved

import os
import subprocess as sp

os.environ['b_dir'] = /path/script/
os.environ['data_dir'] = /path/data/

r0 = sp.run(['echo','$b_dir'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(r0.stdout.decode())
r = sp.run(['ksh','$b_dir/dev/scriptname.ksh'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(r.stdout.decode())

output of r0 was $b_dir

expecting: /path/script/

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
E88
  • 97
  • 1
  • 9
  • Does this answer your question? [Python subprocess/Popen with a modified environment](https://stackoverflow.com/questions/2231227/python-subprocess-popen-with-a-modified-environment) – lllrnr101 Feb 05 '21 at 03:20

1 Answers1

0

You are passing a string to the command 'echo', something like echo '$b_dir' in bash.

You could do it as follows:

r0 = sp.run(["echo", f"{os.environ.get('$b_dir')}"], stdout=sp.PIPE, stderr=sp.STDOUT) 

This os.environ.get('$b_dir') command will read the environment variable and pass its value as an argument in the run method.

Or you can pass the path directly by calling the run method.

r0 = sp.run(["echo", "/my/path/myfile"], stdout=sp.PIPE, stderr=sp.STDOUT)