Python Commands Module
The Python module ‘commands’ allows commands to be ran on the system. I frequently use this in combination with Django to launch processes.
Get a directory listing:
#!/usr/bin/python
import commands
status, output = commands.getstatusoutput('ls')
print "Status: " + str(status)
print "Output: " + str(output)
This program will print out the directory contents of where you ran it from. An important thing to note about programs in Linux in general is that on success they return 0, and anything not 0 is probably an error. I commonly check the status of the returned code:
Check if status is not 0:
if status != 0:
print "An error occurred!"
This allows us to do some really fancy things with this module. For instance, I created an application that is a django app that provides the user a menu to launch programs. This runs on their Firefox browser, but will launch the programs on their system. Each system runs it’s own Cherokee webserver locally, which is extremely lightweight and fast. To install Cherokee to use django I followed this guide: http://www.cherokee-project.com/doc/cookbook_django.html
The users run as the user ‘autologin’, however the webserver runs under the user ‘www’. This is probably a bit hackish, but it works. What I do is copy autologin’s .Xauthority file to the www user’s home directory, then launch the program as autologin using sudo.
Launch a local X program from a django program:
def launchAutologinXProgram(commands):
status, output = commands.getstatusoutput('sudo cp /home/autologin/.Xauthority /home/www/')
os.spawnl(os.P_WAIT, "/usr/bin/sudo", "sudo", "-u", "autologin", "-H", "/bin/bash", "-c", 'export DISPLAY=":0.0"; . /etc/profile; nohup ' + str(commands) + ' &')
Obviously you want to check the status variable and make sure it completed. To do this you need to update your sudoers file to make the www user be able to run commands as autologin. This is for a kiosk type setup, so www and autologin don’t have sensitive data, I am sure there is a more secure way to do it. But it sure is fun.
Related posts:
- Python threads Frequently I need to launch sub processes from Python. Sometimes...
- Creating graphs in python Slow Friday today, so was digging through my $HOME and...
- Python and real time graphical analysis I have a camera which has a motor attached which...
- Installing Play Framework on OpenBSD 4.6 OpenBSD OpenBSD is a free, reliable and secure operating system....
- Python-RPM If you ever get to use this library, it’s design...
#1 by Dennis on February 20, 2009 - 5:54 pm
Quote
The subprocess module is even more fun