Roman
Roman

Reputation: 2375

Print newline if error occurs in python

I have some relatively big program and I used to print its progress to the console in the manner that each function prints only one line of output (it displays "Doing something..." while the function is running (sometimes it displays percentage bar) and turns to "Doing something... Done" when the function finishes successfully. I apply '\r', line clearance, etc. for my progress bar to look nice. However, when error occurs, the message continues the same line, which I want to avoid. For example I have a code:

import os, sys, subprocess
def some_function(filename):
    print('Doing something... ', end = '')
    sys.stdout.flush()
    with open(os.devnull, 'wb') as devnull:
        check = subprocess.call(['ls', filename], stdout = devnull)
        if check != 0:
            sys.exit(1)
    print('Done')
some_function('some.file')

It produces the following output (depending on presence of an error):

Doing something... Done

or

Doing something... ls: some.file: No such file or directory

And what I want to see in the case of error:

Doing something... 
ls: some.file: No such file or directory

Is there some general way to introduce newline in output if error occurs (it can be some internal or user-defined exception as well)?

Upvotes: 1

Views: 939

Answers (2)

khelwood
khelwood

Reputation: 59240

try:
    do stuff that might cause an error
except:
    print()
    raise

If an error is raised inside the try block, this will print a new line, and then re-raise the caught exception.

Edit

As has been pointed out in the comments, in this case the error message is not being generated by a raised exception, so I defer to Padraic's answer.

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

call does not raise an exception so you can catch the error with subprocess using stderr:

import os, sys, subprocess
def some_function(filename):
    print('Doing something... ', end='')
    sys.stdout.flush()
    with open(os.devnull, 'wb') as devnull:
        check = subprocess.Popen(['ls', filename], stdout = devnull, stderr=subprocess.PIPE)
        stdout, stderr = check.communicate()
        if stderr:
            print("\n{}".format(stderr.decode("utf-8")))
            sys.exit(1)
    print('Done')

Upvotes: 4

Related Questions