[Tutor] running more than one python program at the same time

Steven D'Aprano steve at pearwood.info
Tue Sep 4 03:47:32 CEST 2012


On 04/09/12 01:01, Benjamin Fishbein wrote:
> Hi. I started running the program in the terminal rather than IDLE. It works,
> and I can run several programs at the same time. The problem is that when the
>program is finished running, it prints:
> exit status: 0
> logout
>
> [Process completed]


Which terminal is that? I've never come across a terminal with that behaviour.


> And I can't access the data that the program returned.

Programs don't return data. They can output data to a file or pipe, or print to
the screen.

The execution model of functions within a program and of the program itself are
quite different and you need to wrap your brain around the differences.

Normally, you would output your program's result to a file-like thing. Two
common idioms used by most command-line tools are:

1) the program always writes data to "standard output" (stdout); the caller can
    re-direct stdout using the usual pipe and redirection operators;

2) the program takes a command-line argument telling it which file to write to;
    if no file name is given, you can write to a default file, or stdout as
    above, or print an error message and stop.


Variations include "verbose mode", that formats the result in a nice, human-
readable format intended for human readers, and "terse mode" intended to be
piped to another program.

I recommend you study the various conventions of the command-line tools on
your operating system.

In Python, normally you would divide your program into two separate layers:

* a calculation layer that calculates the result you need;

* a display layer that is responsible for output.

That allows you to easily separate the two parts of the problem: you can
isolate "display bugs" from "calculation bugs", test and debug each
separately, and even use the calculation functions from other Python code.

The display layer might be as simple as the print command:


if __name__ == '__main__':
     result = do_some_calculation()
     print(result)


Last but not least, to be a "well-behaved" command line tool, you should
set the return code. The easiest way to do this from Python is with
sys.exit:

import sys

if an_error_occurred:
     sys.exit(error_code)
else:
     sys.exit(0)

There are supposed to be conventions for what the error codes mean,
but nobody agrees on them. The easiest is to just return 1 or 2
to mean "an error occurred".




-- 
Steven


More information about the Tutor mailing list