<p>首先可以使用sleep()或schedule功能来实现函数的连续调用</p>
<p>我编写了一个函数,用于执行控制台命令并返回输出:</p>
<pre><code>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 ''
</code></pre>
<p>现在,如果wifi可用,您只需要一个连接您的功能。请注意,每10到20秒只能调用<code>nmcli rescan function</code>,否则下次它将拒绝扫描任何内容。这就是为什么我建议使用<code>iw module</code>进行扫描</p>
<pre><code>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
</code></pre>
<p>现在你只要经常打电话就行了。。。。e、 g:</p>
<pre><code>def run():
connected = False
while not connected:
connected = tryConnect
time.sleep(10)
run()
</code></pre>