Ubuntu – Running a command at startup not working (due to network not being up when the code was run)

command linenetworkingpythonstartup

I want to run a python script automatically when ubuntu starts up.
Normally what I have to do is open up the command line on ubuntu and type

python /home/ubuntu/Desktop/UDP_Server.py

This will run the python code so I can now start up my other client code to communicate with it.

I want to find a way to do run this code automatically at start up. I have tried putting a script in my /etc/init.d file and I also tried to have it as a startup program as shown below.

Startup Application

But when I turn my computer on this code doesn't run.. because it isn't communicating with my client code like I expect it to (like it does when I run the python script from the command line)

EDIT:

Putting commands such as a touch command in rc.local seems to work at startup.
Also the same is true for crontab. I added a command @reboot and it works.
But this particular code doesn't seem to work at startup (whether I put it in crontab, rc.local, init.d, or as a startup application)

Below is my UDP server code

import socket
import serial
import subprocess

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = (192.168.1.13, 10000)
print 'starting up on %s port %s' % server_address
sock.bind(server_address)

ser = serial.Serial('/dev/ttymxc3', 115200, timeout = 0)
print 'Serial connected'

while True:
    data = sock.recv(7)
    print 'received ', data
    if data == "STOP":
        subprocess.call(["sudo", "shutdown", "-h", "now"])
    else:
        ser.write(data)

When I run this at the command line it works something like this

starting up on 192.168.1.13 port 10000
Serial connected

Then the program waits for a connection.
If I have my UDP Client send STOP

received 'STOP'

The computer then shuts down.

But when the code is run at startup and I send 'STOP' via the UDP Client the computer doesn't shut down. The while loop in the server code with sock.recv somehow isn't receiving the strings that are being sent to it.

SOLUTION:

After I added the following lines of code to my /etc/network/interfaces file

auto wlan0
    iface wlan0 inet dhcp
    post-up python /home/ubuntu/Desktop/UDP_Server.py

The code executed at startup after the wifi network was working so my client was able to communicate with server.

Best Answer

You need to run your command after network interfaces gets up. As described in this answer: https://unix.stackexchange.com/a/91264

Related Question