0

I have shell code which need to be initialised with python variable

Note : the var is a python variable which holds value /d/demo/f.txt

Need to pass the python variable var to my below shell script

var='/d/demo/f.txt'

script="""

( 
echo "From : xyz"
echo "To : xyz"
cat var
) |sendmail -t 

"""
os.system("bash -c '%s' % script ")

The var value assigned is not passed to cat var Any solution is appreciated

oguz ismail
  • 1
  • 16
  • 47
  • 69
  • 1
    Why are you using `os.system()` to send mail? Python has libraries for this. – Barmar Oct 12 '21 at 07:03
  • @Barmar : Because i don't library installed and it's restricted from installing –  Oct 12 '21 at 07:11
  • Huh? `email` and `smtplib` are installed along with Python itself. – tripleee Oct 12 '21 at 07:21
  • Unless the file starts with an empty line, your script is broken. The spaces before the colons are also quite irregular, though I guess they won't block delivery. – tripleee Oct 12 '21 at 07:23

1 Answers1

1

Use an f-string to substitute the variable into the script. Use shlex.quote() to escape it in case it has special characters.

import shlex

var='/d/demo/f.txt'
from='xyz'
to='xyz'

script=rf"""

( 
printf 'From: %s\nTo: %s\n' {shlex.quote(from)} {shlex.quote(to)}
cat {shlex.quote(var)}
) |sendmail -t 

"""
os.system(script)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I added that to the answer. There's no need for `bash -c`. – Barmar Oct 12 '21 at 07:02
  • @Barmar : if i want to take variable to From and To email id's same shlex quote will work – codeholic24 Oct 12 '21 at 07:04
  • Yes, why would it be any different? – Barmar Oct 12 '21 at 07:04
  • @Barmar : The answer seems to be interesting , will test with my environment is it possible to create python function and pass parameter at run time to the embed Unix script. As far i know most of the time i tried creating bas script with .sh and called in python with `os.system(sh script.sh)` – codeholic24 Oct 12 '21 at 07:09
  • @codeholic24 : Can you check and share the script with me it will be helpful for me –  Oct 12 '21 at 07:12