Bryant
Bryant

Reputation: 3601

Sourcing output of python script fails with broken pipe exception

I'm trying to have the output of a python script be sourceable. i.e. I'd like to be able to run:

$ source <(python example.py)

It ALWAYS fails with the same issue:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Here is example.py:

print("export ENV_VAR=abc")

Is there any way around this? I've attempted to try and catch the exception (BrokenPipeError) but it doesn't seem to work. The exception seems to prevent the sourcing from working since

$ echo $ENV_VAR

gives me nothing

Upvotes: 6

Views: 474

Answers (2)

hackerb9
hackerb9

Reputation: 1912

You can fix it in the python script or by sending the output of the python script to a program that does not freak out when its stdout is closed.

source <(python example.py | tee -p /dev/null)

Side note: I could not get source to reproduce the error described, but I was able to replicate the problem using echo

Upvotes: 0

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47159

Maybe eval or export could be used to get the variables from a Python script into the current Bash environment:

export $( python example.py )
echo $ENV_VAR

...or...

eval $( python example.py )
echo $ENV_VAR

There might be a better way to handle this, although both should output "abc".

Upvotes: 1

Related Questions