1

I have a command in my bash_profile such as id=12345 which I defined the following alias

alias obs="echo $id" since the id will chance over time.

Now what I want to do is call this alias in my python script for different purposes. My default shell is bash so I have tried the following based on the suggestions on the web

import subprocess

subprocess.call('obs', shell=True, executable='/bin/bash')

subprocess.call(['/bin/bash', '-i', '-c', obs])

subprocess.Popen('obs', shell=True,executable='/bin/bash')

subprocess.Popen(['/bin/bash', '-c','-i', obs])

However, none of them seems to work! What am I doing wrong!

1
  • Shell aliases are in interactive shell feature. You cannot access them from Python. You can access the environment variable (id), only. Commented Apr 12, 2020 at 14:00

1 Answer 1

2

.bash_profile is not read by Popen and friends.

Environment variables are available for your script, though (via os.environ).

You can use export in your Bash shell to export a value as an environment variable, or use env:

export MY_SPECIAL_VALUE=12345
python -c "import os; print(os.environ['MY_SPECIAL_VALUE'])"
# or
env MY_SPECIAL_VALUE=12345 python -c "import os; print(os.environ['MY_SPECIAL_VALUE'])"
Sign up to request clarification or add additional context in comments.

2 Comments

Or even without the env like this MY_SPECIAL_VALUE=18 python ...
@MarkSetchell Sure, that works in Bash, but env is portable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.