第一次使用可以使用 sleep() 或 schedule 功能来实现函数的继续调用。
我编写了一个执行控制台命令并返回输出的函数:
def _executeConsoleCommand(command):
'''Executes the linux command line arguments and returns the output if needed'''
try:
stream = os.popen(command)
return stream.read().strip()
except:
return ''
现在,您只需要一个在 wifi 可用时连接您的功能。请注意,您只能nmcli rescan function
每 10 到 20 秒调用一次 - 否则它将拒绝下次扫描任何内容。这就是为什么我建议使用iw module
.
def tryConnect():
yourSSID = 'TestWifi'
yourPassword = '12345678'
ssids = _executeConsoleCommand('sudo iwlist wlan0 scan | grep "SSID" | awk \'!a[$0]++\' | cut -d \':\' -f2').split(os.linesep) # scans your deviceses
ssids = [ssid.replace('"', '') for ssid in ssids] # remove the exclaimation marks
if yourSSID in ssids:
_executeConsoleCommand('sudo nmcli device wifi rescan ifname wlan0 ssid {}'.format(yourSSID)) #you have to call this before you connect - thats a thing of nmcli
_executeConsoleCommand('sudo nmcli dev wifi connect {} password "{}" ifname wlan0'.format(yourSSID, yourPassword))
# now check if your connected
ssid_on_interface_wlan0 = 'sudo iw wlan0 info | grep ssid | awk \'{{ print $2 }}\''
if yourSSID in _executeConsoleCommand(ssid_on_interface_wlan0):
return True
return False
现在你只需要经常调用它......例如:
def run():
connected = False
while not connected:
connected = tryConnect
time.sleep(10)
run()