I am writing a program that needs to spawn a new terminal window and launch a server in this new terminal window (with environment variables passed to the child process).
I have been able to achieve this on windows 10 and linux without much trouble but on Mac OS X (Big Sur) the environment variables are not being passed to the child process. Here is an example code snippet capturing the behaviour I want to achieve:
#!/usr/bin/python3
import subprocess
import os
command = "bash -c 'export'"
env = os.environ.copy()
env["MYVAR"] = "VAL"
process = subprocess.Popen(['osascript', '-e', f"tell application \"Terminal\" to do script \"{command}\""], env=env)
Unfortunately, MYVAR
is not present in the exported environment variables.
Any ideas if I am doing something wrong here?
Is this a bug in python's standard library ('subprocess' module)?
edit - thank you Ben Paterson (previously my example code had a bug) - I have updated the code example but I still have the same issue.
edit - I have narrowed this down further. subprocess.Popen
is doing what it is supposed to do with environment variables when I do:
command = "bash -c 'export > c.txt'"
process = subprocess.Popen(shlex.split(command, posix=1), env=env)
But when I try to wrap the command with osascript -e ... (to spawn it in a new terminal window) the environment variable "MYVAR" does not appear in the c.txt
file.
command = "bash -c 'export > c.txt'"
process = subprocess.Popen(['osascript', '-e', f"tell application \"Terminal\" to do script \"{command}\""], env=env)