Home > other >  how to change a sequence of bash commands while running?
how to change a sequence of bash commands while running?

Time:05-24

Let's say I would like to run two python scripts sequentially. My current solution is to write a bash run.sh script which can contain something like:

python foo.py
python bar.py

Now let's say that after executing ./run.sh command in a terminal and while foo.py is running (bar.py hasn't started yet), I would like to run baz.py (which has been created after the execution of the ./run.sh command) instead of bar.py. The run.sh script would now look like this:

python foo.py
python baz.py

My question then is: is it possible? To clarify: is there a way to modify a command line sequence on the fly? This sequence doesn't have to be contained in a bash file and may involve some workflow/pipeline management program that I don't know about.

CodePudding user response:

I suggest using a python solution for this. With threading you can run things in "parallel". I made a run.py file which then can be ran via bash. This is just the principle. You can change the input in the 'run.py' file to something that suites you purpose.

# test1.py
import time
print("This is test1.py running")
time.sleep(10)
print("This is test1.py finishing")
# test2.py
import time
print("This is test2.py running")
time.sleep(10)
print("This is test2.py finishing")
# test3.py
import time
print("This is test3.py running")
time.sleep(10)
print("This is test3.py finishing")
# run.py
import threading

def run1():
    import test1
    
def run2():
    i = int(input("2 or 3: "))
    if i == 2:
        import test2
    elif i == 3:
        import test3
    else:
        print("jumped over 2 and 3")
        
t1 = threading.Thread(target=run1)
t2 = threading.Thread(target=run2)

t1.start()
t2.start()

t1.join()
t2.join()

CodePudding user response:

Have your Python script foo.py write the name of the script you want to a file ./.script, like so:

# imports


with open('./.script.py', 'w') as f:
    f.write('python bar.py')

# do stuff

if condition:
    with open('./.script.py', 'w'):
        f.write('python baz.py')

Then your script can look like

#!/bin/bash
python foo.py
`cat .script`

There is no need to modify it on the fly.

  • Related