0

In linux shell I have

myip=`curl http://169.254.169.254/latest/meta-data/local-ipv4`

But I need to do the same on Python. I'm trying to do

inport os
myip=os.system("curl http://169.254.169.254/latest/meta-data/local-ipv4")

but get nothing. I tried echo, export myip = etc.

  • 2
    Does this answer your question? [Assign output of os.system to a variable and prevent it from being displayed on the screen](https://stackoverflow.com/questions/3503879/assign-output-of-os-system-to-a-variable-and-prevent-it-from-being-displayed-on) In other words, os.system returns an exit code not the stdout of the command. Use the suggestions from that question to obtain the stdout (e.g. `popen`) – SamBob Nov 08 '21 at 11:48
  • 2
    You could also just use the standard library to make the http request instead of relying curl... – juanpa.arrivillaga Nov 08 '21 at 11:50
  • To add to @juanpa.arrivillaga - here's an example of getting your IP using the standard library instead of using curl: https://stackoverflow.com/a/36205547/1581658 – SamBob Nov 08 '21 at 11:51
  • @SamBob that example you link to actually *does not* use the standard library, it uses `requests`, a popular third-party library. [Here's a link to a standard library function you could use instead](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen) – juanpa.arrivillaga Nov 08 '21 at 11:53
  • Thanks - `requests` is such second nature I always forget it isn't in the standard library. (Even though the link I posted literally says that its not!) Heres the full SO answer for this question using the urllib https://stackoverflow.com/a/41432835/1581658 – SamBob Nov 08 '21 at 11:55

0 Answers0