Sina Sh
Sina Sh

Reputation: 1197

Shell script to increment a value inside a python script

I have a simple python script which I'd like to write a shell script to increase a specific value (bearer_id) inside the script incrementally (till a fixed value like 100, 200) and repeat the other lines just as they are (example below). can you please give me some hints/or example of a shell script, on how to do this?

script.py is like:

sgw.add_bearer(dpid=256, bearer_id=1, \
saddr_ingress="10.1.1.10", \
sport_ingress=2152)

Final script should be like this, script.py:

sgwumgt.add_bearer(dpid=256, bearer_id=1, \
saddr_ingress="10.1.1.10", \
sport_ingress=2152)

sgwumgt.add_bearer(dpid=256, bearer_id=2, \
saddr_ingress="10.1.1.10", \
sport_ingress=2152)
.
.#repeat 99 times
.
sgwumgt.add_bearer(dpid=256, bearer_id=100, \
saddr_ingress="10.1.1.10", \
sport_ingress=2152)

p.s: This has to be a separate shell script which I execute it over ssh on the remote machine (which has this python script, ready to execute) then this shell script must either create a new .py file such as I mentioned above or change the existing one in that way for further steps.

Thanks a lot in advance

Upvotes: 0

Views: 213

Answers (2)

shuttle87
shuttle87

Reputation: 15924

Looping constructs exist to solve this exact problem you have:

max_id = 100
for id in range(1, max_id+1):
    sgwumgt.add_bearer(dpid=256, bearer_id=id,
                       saddr_ingress="10.1.1.10",
                       sport_ingress=2152)

If you weren't aware you could do this then you really should spend some time with some python tutorials as this is a very fundamental building block for writing python code.

If the python script has to change the behavior based on a command line parameter you have a few options. You can use argparse or similar or perhaps do something quick with sys.argv. Here's a way you can do this with sys.argv:

import sys
if(len(sys.argv)) == 1:
    max_id == 100 #Default case
elif(len(sys.argv)) == 2:
    max_id = int(sys.argv[1])

Which you can then call on the command line with python script.py 150 which would set max_id to 150. If you need to do more complex argument parsing I would recommend using argparse.

Upvotes: 0

sphennings
sphennings

Reputation: 1083

If the only thing that is changing is the bearer_id than you could use a for loop instead

Something like:

for id in range(1,101):
    sgw.add_bearer(dpid=256, bearer_id=id, \
    saddr_ingress="10.1.1.10", \
    sport_ingress=2152)

This would greatly reduce the amount of code you needed to write as well as make it easier to modify the code later.

Upvotes: 1

Related Questions