I'm having trouble connecting to a wifi via python script right now because most tutorials out there are deprecated. There do not seem to be suitable up-to-date python packages anymore thus I plan to use os.system(command) for connection.

But up until now I just cannot find the right method for my requirements. I want to use interface wlan0 to scan available networks and then connect to one via essid and key. I want to maintain a static IP so that I can still find the pi for ssh connection.

The whole connection thing should be rather easy e.g. via network manager nmcli but I struggle to find a right configuration for my requirements (you got to activate the interface in /etc/network/interfaces right??) without either WIFI breaking or the static IP getting lost.

It would be great if someone can recommend any up-to-date method to do this so that I do not try to get things to work which are deprecated.

Thanks in advance and best regards.

  • 1
    Python programs don't connect to WiFi they use an existing route to send packets from their source to a destination address. Hardware systems connect to WiFi. So you need to clarify what you're asking. The current question only has the answer of "This doesn't make sense".
    – Dougie
    Jan 25 at 16:49
  • An additional note; NOTHING involving Network Manager is simple and it is not normally used on Pi and wouldn't use wlan0
    – Milliways
    Jan 25 at 21:20

1 Answer 1


I could solve it myself. Here's the function I wrote which connects to a given WIFI via ssid and password. It is a bit workaround-like but it works for me so far. Just make sure that the line numbers 6 and 7 match your file structure.

def connect(goal_ssid,goal_pw):
    # "" important in wpa.conf or it would not work
    goal_ssid = '"' + goal_ssid + '"'   
    goal_pw = '"' + goal_pw + '"'
    # Reconfigure goal wifi and key in line 6 and 7 of wpa_supplicant.conf
    cm = "sudo sed -i '6s/.*/        ssid=" + goal_ssid + "/' /etc/wpa_supplicant/wpa_supplicant.conf" # using % does not work with all the "" being important in the wpa.conf
    cm = "sudo sed -i '7s/.*/        psk=" + goal_pw + "/' /etc/wpa_supplicant/wpa_supplicant.conf" # using % does not work with all the "" being important in the wpa.conf

    # Activate new configuration
    cm = "sudo wpa_cli -i wlan0 reconfigure"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.