views:

102

answers:

1

Hello all.

I have been looking through Google and SO for something that could help me solve this but I have run into a block. I am a bit new to Python but I am looking for a way to run multiple apps that will continuously run in the background.

For example, I need 4 apps to start up with a param -appnum set to a different value. I would like to use python to count up and then start up a new app that will continue to run.

I assumed I would use subprocess but I feel a bit overwhelmed by the documentation.

I also plan to have the app print out sequences of numbers and would like to redirect this to a file. I noticed some of the SO questions talked about this, but I am a little confused on what to do.

+1  A: 

A simple way to start might be to use os.popen(), like this:

import os

subprogs = [None] * 4
for i in range(4):
    subprogs[i] = os.popen("app -appnum " + i, "r")

From here, you can read from each subprog[i] just like a file, capturing the output of the app program.

Note that although the documentation says this function has been deprecated, it still works perfectly fine for many purposes. You can explore the subprocess module when you're more familiar with the limitations of os.popen().

Greg Hewgill
+1 Agreed -- start simple!
Kevin Little
Note that `os.popen` is deprecated in favour of the `subprocess` module.
Mike Graham
Also, your `foo = [None] * n` `for i in range(n): foo[i] = f(i)` pattern seems really odd to me, since we typically build lists as we go along in Python. `foo = []` `for i in xrange(n): foo.append(f(i))` seems a lot more in keeping with all the Python code I've read and written.
Mike Graham
@Mike Graham: You're right, there are certainly more Pythonic ways of writing that code. I wanted to do something that was as simple as possible to read, since the OP indicated that he was new to Python. I'd probably have written that using a list comprehension instead of `append()` actually.
Greg Hewgill
@Greg, I don't really see how doing it this way makes things easier on a beginner. `list.__mul__` is a relatively obscure Python feature that seldom pops up in normal code, isn't clear from reading it what it does, and is a common source of beginner bugs. It is used in conjunction with iterating using indices, a pattern common in some languages, in which it's a frequent source of bugs. `list.append`, on the other hand, is self-documenting, constantly useful, and more idiomatic. I must just see this quite differently than you.
Mike Graham