简体   繁体   中英

How to pass Python variable into bash commands?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM