Hi all!
this is a (relatively) newbie question
I am writing a shell in Python and I am facing a problem
The problem is, after taking the input from user, i have to execute the
command which is a python function
i invoke an 'ls' command like this
commands.ls()
where commands.py is a file in the same directory
what i want to do is
commands.VARIABLE()
where VARIABLE holds the name of the function which i want to execute
and depends on what the user has typed
what should i do to achieve that?
any help is appreciated
thank you
-creo
P.S. if you want me to clarify the question, please tell me so 12 1806
creo wrote: i invoke an 'ls' command like this commands.ls() where commands.py is a file in the same directory
what i want to do is commands.VARIABLE() where VARIABLE holds the name of the function which i want to execute and depends on what the user has typed
You want
getattr(commands, VARIABLE)()
Peter
Peter Otten <__*******@web.de> writes: creo wrote: what i want to do is commands.VARIABLE() where VARIABLE holds the name of the function which i want to execute and depends on what the user has typed
You want
getattr(commands, VARIABLE)()
You'll also need to anticipate the situation where the value bound to
VARIABLE is not the name of an attribute in 'commands'.
Either deal with the resulting NameError exception (EAFP[0]) or test
first whether the attribute exists (LBYL[1]).
[0] Easier to Ask Forgiveness than Permission
[1] Look Before You Leap
--
\ "Our products just aren't engineered for security." -- Brian |
`\ Valentine, senior vice-president of Microsoft Windows |
_o__) development |
Ben Finney
Ben Finney wrote: Peter Otten <__*******@web.de> writes:
(snip) You want getattr(commands, VARIABLE)()
You'll also need to anticipate the situation where the value bound to VARIABLE is not the name of an attribute in 'commands'.
Either deal with the resulting NameError exception (EAFP[0])
try:
getattr(commands, VARIABLE)()
except NameError:
print >> sys.stderr, "Unknown command", VARIABLE
or test first whether the attribute exists (LBYL[1]).
command = getattr(commands, VARIABLE, None)
if command is None:
print >> sys.stderr, "Unknown command", VARIABLE
else:
command()
I'd go for the first solution.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
On 2006-05-19, bruno at modulix <on***@xiludom.gro> wrote: Either deal with the resulting NameError exception (EAFP[0])
try: getattr(commands, VARIABLE)() except NameError: print >> sys.stderr, "Unknown command", VARIABLE
or test first whether the attribute exists (LBYL[1]).
command = getattr(commands, VARIABLE, None) if command is None: print >> sys.stderr, "Unknown command", VARIABLE else: command()
I'd go for the first solution.
Me too. Assuming the user isn't clueless, the normal case is
where the command exists. Write code for the normal case and
use the exception that occurs for exceptional cases.
--
Grant Edwards grante Yow! This PIZZA symbolizes
at my COMPLETE EMOTIONAL
visi.com RECOVERY!!
In article <12*************@corp.supernews.com>,
Grant Edwards <gr****@visi.com> wrote: On 2006-05-19, bruno at modulix <on***@xiludom.gro> wrote:
Either deal with the resulting NameError exception (EAFP[0])
try: getattr(commands, VARIABLE)() except NameError: print >> sys.stderr, "Unknown command", VARIABLE
or test first whether the attribute exists (LBYL[1]).
command = getattr(commands, VARIABLE, None) if command is None: print >> sys.stderr, "Unknown command", VARIABLE else: command()
I'd go for the first solution.
Me too. Assuming the user isn't clueless, the normal case is where the command exists. Write code for the normal case and use the exception that occurs for exceptional cases.
Cameron Laird wrote: Guys, I try--I try *hard*--to accept the BetterToAskForgiveness gospel, but this situation illustrates the discomfort I consistently feel: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE() itself didn't throw a NameError? My usual answer: umm, unless I go to efforts to prevent it, I *don't* know that didn't happen.
two notes:
1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.
2) as you point out, doing too much inside a single try/except often results in hard-
to-find errors and confusing error messages. the try-except-else pattern comes in
handy in cases like this:
try:
f = getattr(commands, name)
except AttributeError:
print "command", name, "not known"
else:
f()
</F>
[Cameron] try: getattr(commands, VARIABLE)() except NameError: print >> sys.stderr, "Unknown command", VARIABLE
this situation illustrates the discomfort I consistently feel: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE() itself didn't throw a NameError? My usual answer: umm, unless I go to efforts to prevent it, I *don't* know that didn't happen.
The 'try' block should only include the code that you expect to fail with
the given exception. Try this instead: try: command = getattr(commands, VARIABLE) except AttributeError: print >> sys.stderr, "Unknown command", VARIABLE else: command()
(Aside: I think AttributeError is correct here, not NameError.)
--
Richie Hindle ri****@entrian.com
Fredrik Lundh wrote: Cameron Laird wrote:
Guys, I try--I try *hard*--to accept the BetterToAskForgiveness gospel, but this situation illustrates the discomfort I consistently feel: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE() itself didn't throw a NameError? My usual answer: umm, unless I go to efforts to prevent it, I *don't* know that didn't happen.
two notes:
1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.
oops ! My bad :(
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
bruno at modulix <on***@xiludom.gro> writes: Ben Finney wrote: You'll also need to anticipate the situation where the value bound to VARIABLE is not the name of an attribute in 'commands'.
Either deal with the resulting NameError exception (EAFP[0])
try: getattr(commands, VARIABLE)() except NameError: print >> sys.stderr, "Unknown command", VARIABLE
No. As another poster points out, that will mistakenly catch NameError
exceptions raised *inside* the function.
When catching exceptions, be sure that your 'try' block is only doing
the minimum of stuff that you want exceptions from, so you know what
they mean when they occur.
try:
this_command = getattr(commands, VARIABLE)
except NameError:
print >> sys.stderr, "Unknown command '%s'" % VARIABLE
this_command() or test first whether the attribute exists (LBYL[1]).
command = getattr(commands, VARIABLE, None) if command is None: print >> sys.stderr, "Unknown command", VARIABLE else: command()
I'd go for the first solution.
With the caveats mentioned above, yes, I agree.
--
\ "I was arrested today for scalping low numbers at the deli. |
`\ Sold a number 3 for 28 bucks." -- Steven Wright |
_o__) |
Ben Finney
"Fredrik Lundh" <fr*****@pythonware.com> writes: Cameron Laird wrote: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE() itself didn't throw a NameError? My usual answer: umm, unless I go to efforts to prevent it, I *don't* know that didn't happen.
two notes:
1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.
2) as you point out, doing too much inside a single try/except often results in hard- to-find errors and confusing error messages. the try-except-else pattern comes in handy in cases like this:
try: f = getattr(commands, name) except AttributeError: print "command", name, "not known" else: f()
Gah. As is often the case, Frederick has avoided my mistakes and said
what I wanted to say, better.
--
\ "There are only two ways to live your life. One is as though |
`\ nothing is a miracle. The other is as if everything is." -- |
_o__) Albert Einstein |
Ben Finney
Fredrik Lundh wrote: Cameron Laird wrote:
Guys, I try--I try *hard*--to accept the BetterToAskForgiveness gospel, but this situation illustrates the discomfort I consistently feel: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE() itself didn't throw a NameError? My usual answer: umm, unless I go to efforts to prevent it, I *don't* know that didn't happen.
two notes:
1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.
2) as you point out, doing too much inside a single try/except often results in hard- to-find errors and confusing error messages. the try-except-else pattern comes in handy in cases like this:
try: f = getattr(commands, name) except AttributeError: print "command", name, "not known" else: f()
What if commands were an instance of this class:
class CommandClass:
....
def __getattr__(self,attr):
try:
return self.dircontenst[attr]
except KeyError:
raise AttributeError
The call to getattr manages to raise AttributeError even though the
command is known. Yes, self.dircontents[attr] does exist and is valid
in this example, but it still raises AttributeError because dircontents
is spelled wrong.
I make this silly example to point out that Python's dynamicism is a
possible pitfall with ETAFTP even if you're careful. It's something
worth keeping in mind.
Another example, much more realistic: GvR says don't use callable(),
just try calling it and catch CallableError (or whatever it is). Of
course, that error can be raised inside the function; and in this case,
there's no way to isolate only the part you you're checking for an
exception.
Carl Banks
Dennis Lee Bieber wrote: On Fri, 19 May 2006 14:41:13 +0000, cl****@lairds.us (Cameron Laird) declaimed the following in comp.lang.python: . Guys, I try--I try *hard*--to accept the BetterToAskForgiveness gospel, but this situation illustrates the discomfort I consistently feel: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE()
I'd suggest that each of your "valid" commands should contain whatever error checking is appropriate to it -- and if needed, raise some custom "command failure" exception after handling the real failure internally.
That probably doesn't help when the exception is due to a bug and not
bad input. If you have an AttributeError due to a bug, it would be
wrong to raise a custom command failure exception.
Carl Banks This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Brandon J. Van Every |
last post by:
I'm realizing I didn't frame my question well.
What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump
up in your chair and scream "Wow! Ruby has *that*? That is SO...
|
by: Kyler Laird |
last post by:
I need to submit C/C++ code for a class. (It's not a programming
class. The choice of language is inertial. I think that it mostly
serves to distract students from the course subject.) I'm...
|
by: Natsu Mizutani |
last post by:
Hello,
I'm trying to wrap a c++ library using MPI inside with boost.python
(or SWIG).
I managed to find that calling `MPI::Init()` embeded in a c++ funtion
would not work. So, I decided to use...
|
by: David MacQuigg |
last post by:
I am starting a new thread so we can avoid some of the non-productive
argument following my earlier post "What is good about Prothon". At
Mr. Hahn's request, I will avoid using the name "Prothon"...
|
by: delrocco |
last post by:
Hello,
I really appreciate anyone who has time to read this and help, Thanks
up front.
I'm very new to python, having picked it up for the first time a week
ago, but I feel I'm very close to...
| |
by: Yevgeniy (Eugene) Medynskiy |
last post by:
Hi all,
This is probably a very newbie question, but after searching google and
docs @ python.org I can't find an answer, so maybe someone would be able
to help?
I'd like to call command-line...
|
by: phoolimin |
last post by:
Dear all,
I am trying to embed python into another scripting language, to do this
I need to solve a number of problems on importing or compiling python
script. First let me state what exactly I...
|
by: Anthony Smith |
last post by:
In my php page I am calling a Python cgi. The problem is that
originally the Python script was being called directly and it could
access the environment variables that were being set. Now since the...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
| |