user3082677 user3082677 - 1 year ago 152
Python Question

Execute subprocess sequentially in python

I am trying to the following 2 commands in python one after another.

runmqsc <Queuem manager name>
Display QL (<queue name>)

I can execute the rumqsc command using subprocess."runmqsc <queue manager name>", shell= True)

Now this commands seems like taking the control from python. If i try to execute the next command using subprocess its not working as expected.
I am not even sure how to execute the second(for which i have to pass an argument).

Adding the code snippet:"runmqsc Qmgrname", shell= True)"DISPLAY QL(<quename>)",shell=True)

Now the first line executes fine and as mentioned by tdelaney in the comment runmqsc waits for input from stdin. And after executing the first line the program hangs without even executing the second line.

Any help or references to any of the related document would help.

Answer Source

You don't want to run to subprocess commands sequentially. When you run runmqsc on the command line, it takes over stdin, executes the commands you enter and then finally exits when you tell it to. From the docs:

By taking stdin from the keyboard, you can enter MQSC commands interactively. By redirecting the input from a file, you can run a sequence of frequently used commands contained in the file. You can also redirect the output report to a file.

But I think there's a third way. Start runmqsc, write your command(s) to stdin then close stdin. It should execute the commands and exit. It turns out that Popen.communicate does this for you. I don't know if you want to capture the output but in this example I'm letting it go to the screen.

# start msg queue manager
mqsc = subprocess.Popen(["runmqsc", "QMAGTRAQ01"], stdin=subprocess.PIPE,
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# pass command(s) to manager and capture the result
out, err = mqsc.communicate("DISPLAY QL(BP.10240.012.REQUEST)")
# wait for command to complete and deal with errors
retcode = mqsc.wait()
if retcode != 0:
    print("-- ERROR --") # fancy error handling here
print("OUTPUT: ", out)
print("ERROR: ", err)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download