Saturday, November 12, 2011

Resetting wireless interface in Ubuntu

Most often in Ubuntu, the wireless stops working. Either it shows
Wireless Networks - Disconnected
and does not display any wireless connections available, or the wireless connection speed slows down drastically and resets quite frequently. This happens when the laptop wakes from a sleep or I try to unlock the screen after a brief period of inactivity.

One way to get out of this situation without rebooting is to restart the wireless lan interface (wlan0) using the commands:
sudo ifdown wlan0
sudo ifup wlan0

(or)

sudo ifconfig wlan0 down
sudo ifconfig wlan0 up

Reference:
1. http://askubuntu.com/questions/33818/lost-wireless-connection-and-detection

Retrieving deleted files from Ubuntu

If files are deleted from GUI by pressing the DELETE key, then those files can be recovered without the need for any additional recovery tools like Scalpel.

Linux version can be obtained by
uname -a

My Linux version is ubuntu 2.6.32-34-generic - Lucid (10.04).

In this linux version, when files/folders are deleted from GUI (by pressing the DELETE key - not sure about SHIFT+DELETE), the contents go to the Trash folder. The path for this trash folder is
~/.local/share/Trash/files

You should be able to find the deleted contents there.


Wednesday, November 2, 2011

Running shell commands in Python

You can run shell commands in Python using the "os" library:

import os
os.system("command") 

If we need to capture the stdout or the stderr outputs in the python code, we need to use subprocesses.

from subprocess import Popen, PIPE, STDOUT

cmd = 'echo "Hello World"'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
print output

To stream the output in realtime:

import sys
from subprocess import Popen, PIPE, STDOUT

cmd = 'echo "Hello World"'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
for line in iter(p.stdout.readline, ''):
    sys.stdout.write(line)

In few cases, we might need to stop/kill the subprocess opened using Popen. Such cases arise when we need to execute some system command from python, but do not want that command to take more than 30 seconds/1 minute. One dumb way to make this stopwatch/timer work is to run a while loop in the main python program. The code looks like:

import time
from subprocess import Popen, PIPE, STDOUT

p = Popen('COMMAND', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
time_start = time.time() 
seconds_passed = 0 
while(not p.poll() and seconds_passed<30):
    seconds_passed = time.time() - time_start 
if(seconds_passed>=30):    
    p.kill()   
else:
    output = p.stdout.read()


Reference: