Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python -V write to the error stream?

Tags:

python

I was writing a script to inspect python's version on my system and I've noticed that python -V writes to the error stream, while python -h, for instance, uses the standard output. Is there a good reason for this behavior?

like image 968
guillermooo Avatar asked Nov 04 '09 09:11

guillermooo


2 Answers

The -h option also used to print to stderr because it is not part of the output of your program, i.e. the output is not produced by your Python script but by the Python interpreter itself.

As for why they changed the -h to use stdout? Try typing python -h with your terminal window set to the standard 24 lines. It scrolls off the screen.

Now most people would react by trying python -h |less but that only works if you send the output of -h to the stdout instead of stderr. So there was a good reason for making -h go to stdout, but no good reason for changing -V.

like image 59
Michael Dillon Avatar answered Sep 30 '22 18:09

Michael Dillon


-h used to print to stderr too as you see here from main.c

usage(int exitcode, char* program)
{
fprintf(stderr, usage_line, program);
fprintf(stderr, usage_top);
fprintf(stderr, usage_mid);
fprintf(stderr, usage_bot, DELIM, DELIM, PYTHONHOMEHELP);
exit(exitcode);
/*NOTREACHED*/
}

...

if (help)
    usage(0, argv[0]);

if (version) {
    fprintf(stderr, "Python %s\n", PY_VERSION);
    exit(0);

The current main.c has changed the way usage is defined

usage(int exitcode, char* program)
{
FILE *f = exitcode ? stderr : stdout;

fprintf(f, usage_line, program);
if (exitcode)
    fprintf(f, "Try `python -h' for more information.\n");
else {
    fputs(usage_1, f);
    fputs(usage_2, f);
    fputs(usage_3, f);
    fprintf(f, usage_4, DELIM);
    fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
}

So usage uses stdout for -h and stderr for -Q.

I can't see any evidence of a good reason one way of the other. Possibly it cannot be changed now without breaking backward compatibility

like image 20
John La Rooy Avatar answered Sep 30 '22 18:09

John La Rooy