[Tutor] *nix-specific Python Scripting
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu May 12 20:06:57 CEST 2005
On Thu, 12 May 2005, William O'Higgins wrote:
> I am trying to learn Python by translating some of my Perl scripts. One
> thing that is eluding me is assigning the results of system calls to
> variables. Here's what I want to do in Perl:
>
> $isxrunning = `ps -C startx | grep "startx"`;
>
> if ($isxrunning =~ "startx") {
> do something;
> } else {
> do something else;
> }
> It is a simple check to see if the X server is running (this
> is inelegant, but it works - if you have a better way, I'd love to know
> about it, but I would like to be able to do things like this in Python -
> so I might better write scripts with it).
Hi William,
You may want to look at the 'subprocess' module, or the 'popen2' module.
I wrote a quick-and-dirty example of this yesterday:
http://mail.python.org/pipermail/tutor/2005-May/038343.html
which should apply to your problem.
> My experiments have lead me to the os.exec* collection of methods, and
> they seem fine,
os.exec*() is almost certainly not what you want. *grin*
A call to an exec*() function doesn't just call out to an external
program, but completely replaces the currently running Python program.
Once we do an exec*, we don't get back to Python. (Actually, you can do
things with the exec*() functions, but you'll probably end up doing too
much work with fork() too if you take that route.)
> Don't get me wrong, I'm in this to find out how things of this ilk are
> done in *Python* (if I wanted to know how this was done in Perl, I'd be
> asking somewhere else), I'm not whining for features.
Don't worry; We're tutors and programmers first. We're not averse to
seeing code in other languages, as long as the code snippets are
tastefully short. *grin*
Best of wishes!
More information about the Tutor
mailing list