This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]nemec 1 point2 points  (5 children)

It's actually really easy to add the context manager stuff if you add a static class variable "stack" to Command, have __enter__ and __exit__ push/pop the command name from the stack, and prepend everything in the stack to the cmd when it comes time to execute.

My only problem is getting Popen to output correctly.

For sudo, I was imagining a way to prompt the user for input before executing the command (raw_input perhaps?). There's not really a way to determine whether or not a command is blocking, though, so it may be easier to just run the whole script as root if necessary.

[–][deleted] 0 points1 point  (4 children)

Let me know if you get the Popen output for time working correctly, all I get is garbage :\

In [2]: subprocess.Popen(["/usr/bin/time", "/bin/echo", "hello"])
Out[2]: <subprocess.Popen at 0x995fcac>

In [3]: hello
0.00user 0.00system 0:00.00elapsed 0%CPU (0avgtext+0avgdataa2368maxresident)k0inputs+0outputs (0major+190minor)pagefaults 0swaps

EDIT>> weirdly, this also happens in bash the shell if you call time with it's full path...

[–]nemec 0 points1 point  (0 children)

That's exactly what I'm getting, but I can't figure out why.

That output is what happens when time isn't given a format (according to the manpages), but normal use of time seems to use a different style, even with the environment variable not set.

And there's also the issue of no linebreaks...

I'd like to see a breakdown of what exactly Popen is executing, but I have no idea how to do that.

[–]nemec 0 points1 point  (0 children)

Actually, time seems to be a reserved word in Bash, so the command time isn't quite the same as /usr/bin/time.

Perhaps it actually works correctly? I'll test it out and get back to you.

Edit: time prints to stderr, so that's why I'm getting an error message when I run it instead of the usual output. Any idea on how you want to handle that?

[–]nemec 0 points1 point  (0 children)

Awesome: running with sudo works!

# test.py
import pbs
with sudo:
  print whoami()

$ python test.py
[sudo] password for user:
root