On Stackoverflow I found question: How do I get Geoclue Geolocation in Python?
After installing module to work with GeoGlue
apt install gir1.2-geoclue-2.0
I created script geolocation.py in python
#!/usr/bin/env python
import gi
gi.require_version('Geoclue', '2.0')
from gi.repository import Geoclue
clue = Geoclue.Simple.new_sync('something', Geoclue.AccuracyLevel.NEIGHBORHOOD, None)
location = clue.get_location()
latitude = location.get_property('latitude')
longitude = location.get_property('longitude')
print('{},{}'.format(latitude, longitude))
which gives latitude,longtiture in bash
python getlocation.py
and I can use it directly with wttr.in
curl wttr.in/$(python getlocation.py)
If I set attribute executable
chmod u+x geolocation.py
then I can even run it without python - it will use value from shebang (#!/usr/bin/env python)
I can even remove extension .py and keep name geolocation and then it will looks like
curl wttr.in/$(getlocation)
(it has to be in $( ) to execute it as separated process)
I can also use directly python to get value from server
#!/usr/bin/env python
import gi
gi.require_version('Geoclue', '2.0')
from gi.repository import Geoclue
clue = Geoclue.Simple.new_sync('something', Geoclue.AccuracyLevel.NEIGHBORHOOD, None)
location = clue.get_location()
latitude = location.get_property('latitude')
longitude = location.get_property('longitude')
#print('latitude :', latitude)
#print('longitude:', longitude)
import requests
url = 'https://wttr.in/{},{}'.format(latitude, longitude)
# to get it as HTML instead of TEXT (see PLAIN_TEXT_AGENTS in https://github.com/chubin/wttr.in/blob/master/lib/globals.py#L75)
#response = requests.get(url, headers={'User-Agent': ''}) #{'User-Agent': 'Mozilla/5.0'}
response = requests.get(url)
print(response.text)
If I would add ?format=j1 at the end of url
https://wttr.in/{},{}?format=j1
then I would get it as JSON which I could convert to dictionary in python and I would format data in different way.
Tested on Linix Mint 20, Python 3.8, Python 2.7
By The Way:
It seems wttr.in uses program wego which runs in terminal.
It seems geoclue uses different methods to recognize location but in my situation it probably used IP to recognize it - but my Internet Provider can change my IP every 24h and this IP can be used by users in different places so sometimes it gives incorrect locations. In this moment it gives me location almost 30km away from my place - and later wttr.in gives different weather.
Some web servers use GeoIP from MaxMind to convert IP to location - but it has the same problem when user IP is changed every few hours. As I remeber it can be used by HTTP requests or you can download database with information and use it locally (but you have to update database from time to time)