0

I am questioning of how I can create two variables containing two of the four input values. They are lat1 long1 lat2 long2 to calculate distance. Here is the code:

from geopy import distance


coords_1 = (lat1, long1)
coords_2 = (lat2, long2)

print (distance.distance(coords_1, coords_2).km)

Imagining that I would execute the code as

python3.9 distance.py -1 -28 -4 -32

where -1=lat1, -28=long1, -4=lat2, -32=long2.

Then, how can I include the input coordinates on the four variables?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
gwsmelo
  • 13
  • 4

2 Answers2

0

Text you give into the program on the command line will be stored in sys.argv, along with the script's name. You can get, for example "-1", from sys.argv[1]. sys.argv[0] will be the script name.

import sys
# ...

coords_1 = (int(sys.argv[1]), int(sys.argv[2]))
# adapt for coords_2

# ...
0x150
  • 589
  • 2
  • 11
  • It works if all coordinates are integer. However, the coordinates are not integer and it shows the following error: coords_1 = (int(sys.argv[1]), int(sys.argv[2])) ValueError: invalid literal for int() with base 10: '-28.33' – gwsmelo Aug 11 '23 at 18:36
  • @gwsmelo Then use `float` instead of `int`. – wjandrea Aug 11 '23 at 18:38
0

You can get the arguments from the 'sys' module. In your case:

import sys

coords_1 = (sys.argv[1], sys.argv[2])
coords_2 = (sys.argv[3], sys.argv[4])

Or, for more readable code, you can do:

import sys

lat1 = sys.argv[1]
long1 = sys.argv[2]
lat2 = sys.argv[3]
long2 = sys.argv[4]

coords_1 = (lat1, long1)
coords_2 = (lat2, long2)

These will be strings by default, so you will also probably want to convert them to ints with int().

You can read more about commandline arguments here.

spikehd
  • 234
  • 1
  • 6