dmmpie
dmmpie

Reputation: 445

Running a zsh script from a python script

I have a shell function that I would like to test from within a python script. It contains the double bracket [[ syntax which can only be interpreted by bash/zsh/ksh etc., but not the regular shell. In the original file, I read the function from a sh file using the builtins.open function. I simplified this case a bit and already added the file to the script as a string exactly the way it is loaded in the original file. I then paste it into subprocess with the shell argument set to True:

shell_function = """example_shell_function () {
  #calling a python script which prints values to stdout
  output_string=$(python3 test.py);
  output_snippet=$(echo $output_string | tail -n1)
  test_sign="@"
  #if output_snippet contains "@" then enter condition
  if [[ "$output_snippet" =~ "$test_sign" ]]
  then
    echo "condition met"
  else
    echo "condition not met"
  fi
}"""
shell_commands = "\n".join(shell_function+["example_shell_function"])
    process = subprocess.Popen(shell_commands_test_argument,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE, shell = True)
    stdout, stderr = process.communicate()

I am running zsh on my machine, but subprocess uses the regular sh binary and returns the error [[: not found on the line where the double brackets are defined in the script. I have tried modifying the subprocess call as following, in order to make sure the function is interpreted by zsh instead of sh:

shell_commands = "\n".join([". /bin/zsh"]+shell_function+["example_shell_function"])

This returns the error /bin/sh: 2: /bin/zsh: : not found, in spite of the zsh binary being present at that location. What is the best way to run this function from within my python script?

Upvotes: 1

Views: 1713

Answers (1)

dmmpie
dmmpie

Reputation: 445

Solution proposed by @MarkSetchell worked:

Use executable='/usr/bin/zsh' in your subprocess() call.

Upvotes: 2

Related Questions