How to import whole namespace into global symbol table? (newbie)

S

Scott Simpson

Suppose I have the following python program:

def func():
from sys import stderr, exit
try:
f = open("foo", 'r')
except IOError:
print >> stderr, "Input file foo does not exist"
exit(1)

def main():
import sys

if len(args) != 0:
sys.exit(1)

func()

if __name__ == '__main__':
main()

Notice that I have two "import sys" statements, one for each function.
Is there any way to import the "sys" stuff to the global symbol table so
I don't need two "import" statements?

Lastly, is there an equivalent of Perl's "die" function? I'm writing to
stderr and dieing above but I'm not quite sure if this is the "correct" way.
 
E

Edward Elliott

Scott said:
def func():
from sys import stderr, exit
try:
f = open("foo", 'r')
except IOError:
print >> stderr, "Input file foo does not exist"
exit(1)

IOError can be raised when foo exists, e.g. if there's a permission problem.
It's better to print the actual error message:
.... print >>stderr, e
[Errno 13] Permission denied: 'foo'

Notice that I have two "import sys" statements, one for each function.
Is there any way to import the "sys" stuff to the global symbol table so
I don't need two "import" statements?

move import outside your function scopes.

Lastly, is there an equivalent of Perl's "die" function? I'm writing to
stderr and dieing above but I'm not quite sure if this is the "correct"
way.

you can reraise the exception and get a stack trace. if you want to
replicate die "something\n"; (no stack trace), I'm not sure if there's a
single-function python equivalent.
 
P

Peter Otten

Scott said:
Lastly, is there an equivalent of Perl's "die" function? I'm writing to
stderr and dieing above but I'm not quite sure if this is the "correct"
way.

You can call sys.exit() with a string. Python will print it to stderr and
terminate with a nonzero exit status.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top