doglas doglas - 2 months ago 5
Python Question

python: [try + except] How to make sure all command under try is executed?

This is a very beginners' question. But I cannot find answer...

I want to run ALL lines under

try
. If ANY lines are unexecutable, run
except
.

For example, I have some codes like this...

for i in range(0,100):
try:
print "a"
print "b"
print i, C
print "d"
except:
print i, "fail"


I want to have ALL the lines under
try
executed. In this example,
print C
is unexecutable, because
C
is not pre-defined.

Thus, I want to ONLY run
print i, "fail"
under
except
, because
NOT ALL
lines under
try
are executable.

To be more clearly, The code above gives me the result:

a
b
0 0 Fail
a
b
1 1 Fail
a
b
2 2 Fail
...


But I want to have a result like this:

0 Fail
1 Fail
2 Fail
...


How can I do this? Thanks.

UPDATE:

To be more clearly, I am not asking for a result, I am asking for a method. I think there should be some commands to control
try
.

Answer

You could temporarily redirect stdout and only print in the except:

import sys
from StringIO import StringIO


for i in range(0,100):
    sys.stdout = StringIO()
    try:
        print "a"
        print "b"
        print i, C
        print "d"
    except Exception as e:
        sys.stdout = sys.__stdout__
        print i, "fail" # or print e
sys.stdout = sys.__stdout__

Which would give you:

0 fail
1 fail
2 fail
3 fail
4 fail
5 fail
6 fail
7 fail
8 fail
9 fail
10 fail
11 fail
12 fail
13 fail
14 fail
15 fail
16 fail
17 fail
18 fail
19 fail
20 fail
21 fail
22 fail
23 fail
24 fail
25 fail
26 fail
27 fail
28 fail
29 fail
30 fail
31 fail
32 fail
33 fail
34 fail
35 fail
36 fail
37 fail
38 fail
39 fail
40 fail
41 fail
42 fail
43 fail
44 fail
45 fail
46 fail
47 fail
48 fail
49 fail
50 fail
51 fail
52 fail
53 fail
54 fail
55 fail
56 fail
57 fail
58 fail
59 fail
60 fail
61 fail
62 fail
63 fail
64 fail
65 fail
66 fail
67 fail
68 fail
69 fail
70 fail
71 fail
72 fail
73 fail
74 fail
75 fail
76 fail
77 fail
78 fail
79 fail
80 fail
81 fail
82 fail
83 fail
84 fail
85 fail
86 fail
87 fail
88 fail
89 fail
90 fail
91 fail
92 fail
93 fail
94 fail
95 fail
96 fail
97 fail
98 fail
99 fail

But there are no doubt much better ways to do whatever it is you are trying to do in your real logic.

Bar seeing into the future you cannot print in real time if all calls are going to be successful as you have not seen them all so you would need to store the output and see if there were any errors.

import sys
from StringIO import StringIO

stdo = StringIO()
errs = False
for i in range(0, 100):
    sys.stdout = stdo
    try:
        print "a"
        print "b"
        print i
        print "d"
    except Exception as e:
        sys.stdout = sys.__stdout__
        errs = True
        print i, "fail"
        sys.stdout = stdo

sys.stdout = sys.__stdout__
if not errs:
    print(stdo.getvalue())

Any error will show in real time but you will have to wait until the end to see if all are successful.