Home > Software design >  How to pass python variable to bash shell part of the same file?
How to pass python variable to bash shell part of the same file?

Time:06-19

I have python app that runs some bash commands. Bash shell commands get network bandwidth so it need device name (enp35s0) of my gnu/linux machine.

I run python app typing sudo main.py en35s0 then enp35s0 going to 'n' variable. Below in the same file I have to pass n variable to bash part of app.

main.py

    #!/usr/bin/python3
    import os
    import sys
    import subprocess
    import time
    
    n = (sys.argv[1])
    print(n)
    
    
    def capture():
        subprocess.run(["pkexec", '/bin/bash', '-c', bash], check=True)
    
    bash = '''
    #!/usr/bin/env bash
    #set -x
    
    INTERVAL="1"  # update interval in seconds
    
    
    #-----HERE I MUST PASS N VARIABLE----
    
    n=enp35s0
    
    # How many time script will work.
    start=1
    end=8 # put the number for minues. 3600 is 1 hour.
    
    
    
    while [[ $start -le $end ]]
    do
        #echo "$start"
        ((start = start   1))
    
        # Capture packets.
        R1=`cat /sys/class/net/$n/statistics/rx_bytes`
        T1=`cat /sys/class/net/$n/statistics/tx_bytes`
        sleep $INTERVAL
        R2=`cat /sys/class/net/$n/statistics/rx_bytes`
        T2=`cat /sys/class/net/$n/statistics/tx_bytes`
        TBPS=`expr $T2 - $T1`
        RBPS=`expr $R2 - $R1`
        TKBPS=`expr $TBPS / 1024`
        RKBPS=`expr $RBPS / 1024`
        echo "TX $1: $TKBPS kB/s RX $1: $RKBPS kB/s"
....
....
....

capture()

CodePudding user response:

Use .format like this

#!/usr/bin/python3

default_var = 'AAA'

some_text_var = '''
some text
insert your new var here {value}
some more text
'''.format(value=default_var)

Testing:

>>> print(some_text_var)

some text
insert your new var here AAA
some more text

CodePudding user response:

Example.

#!/usr/bin/python3
import sys
import subprocess

n = ""    
script = "date.sh"   # /path/to/your/shell/script.sh
if len(sys.argv) > 1:
    n = sys.argv[1]

def capture():
    subprocess.run(["/bin/bash", script, n], check=True)
capture()

My shell sctipt

$ cat date.sh
date $@

Exec

$ ./test.py 
Sat 18 Jun 2022 09:48:51 PM CEST

$ ./test.py " %Y"
2022
  • Related