Home > database >  How to pass Python variable into bash commands?
How to pass Python variable into bash commands?

Time:07-28

I've seen some answers about subprocess.call and popen, but I have a list of commands and I think it's not a good idea to have multiple calls or etc. Also I don't want to have a separate script.sh with these commands.

My code looks like

bash_code=r'''
echo "/common_home/{context['nickname']}  /tmp/back/{context['nickname']}  none bind 0 0" | sudo tee --append /etc/fstab
sudo mkdir /tmp/{context['nickname']}  /tmp/back/{context['nickname']}
'''
subprocess.run(['bash', '-c', bash_code], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

But it has much more line with {context['nickname']} and I don't know best way how to parse this variable into bash commands.

CodePudding user response:

You can use a so-called "f-string" to replace the variable references with their values.

context = {'nickname': 'foobar'}

bash_code = f'''
echo "/common_home/{context['nickname']}  /tmp/back/{context['nickname']}  none bind 0 0" | sudo tee --append /etc/fstab
sudo mkdir /tmp/{context['nickname']}  /tmp/back/{context['nickname']}
'''

print(bash_code)
subprocess.run(['bash', '-c', bash_code], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Value printed:

echo "/common_home/foobar  /tmp/back/foobar  none bind 0 0" | sudo tee --append /etc/fstab
sudo mkdir /tmp/foobar  /tmp/back/foobar
  • Related