1

I'm quite new to shell scripting. I have to execute shell scripts using Python. The order of shell scripts is important. Here is my example Python code

import subprocess
import os

script1=  "scripts/script1.sh"
script2 = "scripts/script2.sh"
script3 = "scripts/script3.sh"

subprocess.call([script1])
subprocess.call([script2])
subprocess.call([script3])

The Problem is with above code all scripts are executed separately one after the other but I want to run all under one process.

For example, script2 and script3 should be executed while script one is running.

SRehman
  • 389
  • 1
  • 3
  • 7
  • 1
    How does "under one process" mean "executing while the other script is running"? Those seem completely contradictory. And how can you preserve order if you want to run them all simultaneously? – Daniel Roseman Feb 29 '16 at 12:14
  • @Daniel Roseman yes by "under one process" I mean "script2 & script3 runs while script1 is running". Actually in my implementation script1 opens GUI of a debug program and that program is waiting for some commands which are executed by script2. – SRehman Feb 29 '16 at 12:30
  • You should clarify your question then. A shell script is always a separate process. You can have multiple concurrent processes running, by running some processes in the background (this is an interactive shell concept -- it basically means, fork and don't wait), or by using a pipeline. `subprocess.call()` waits for a process to finish, but the underlying `Popen` will start as many processes as you like without waiting, unless you specifically ask it to. – tripleee Feb 29 '16 at 13:00
  • @tripleee yes it worked after I started script1 with `subprocess.Popen([script1])` which ran script1 as background process. Thanks – SRehman Mar 03 '16 at 19:11
  • "under one process" sounds like you want to start a single shell process and `source` all given scripts. If you mean run concurrently ("while script one is running") then it is a duplicate of http://stackoverflow.com/q/14533458/4279 Leave a comment if it is not what you want. – jfs Mar 04 '16 at 11:25

2 Answers2

1

While the OP apparently refuses to clarify his question, he left a comment indicating that he was looking for subprocess.Popen().

procs = []
for cmd in ['scripts/script1.sh', 'scripts/script2.sh', 'scripts/script3.sh']:
    procs.append(subprocess.Popen([cmd]))

You should eventually wait for the processes you have started.

tripleee
  • 175,061
  • 34
  • 275
  • 318
-1

Seem you need parallel processes. Look at multiprocessing module. Here is the good examples: [https://pymotw.com/2/multiprocessing/basics.html][1]

minskster
  • 512
  • 3
  • 6