0

I have a command like

command = "su - user; cd $CONFIG; grep domain domains.xml"

And need to execute the commands one after other and capture the output of grep.

    def subprocess_cmd(command):
        fnlogs("comand = " + command)
        process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
        proc_stdout = process.communicate()[0].strip()
        fnlogs("proc_stdout = " +proc_stdout + "\n")

subprocess_cmd('su - user; cd $CONFIG; grep domain domains.xml')

Output says grep: domains.xml: No such file or directory, although the file exists its not able to find it.

Sameer
  • 21
  • 1
  • 8

1 Answers1

0

It seems that you are not passing a value for CONFIG.

If you know the intended value within the script, you can do

d = dict(os.environ)
d["CONFIG"] = "/some/directory"
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True, env=d)

You might also have to call sudo with -E to preserve the environment that you pass to the first outermost shell (see https://stackoverflow.com/a/8633575/693140).

On a more general note, you subcommand does not seem to do anything that you could not achieve within Python without relying on external commands. I would recommend to reconsider your approach altogether, and just open the file and extract the respective text from the string (eg using regular expressions).

Stefan Kögl
  • 3,455
  • 1
  • 23
  • 32