1

I've tried to do the above by using this:

print("Ext IP Address is:" + os.system("wget -O - -q https://checkip.amazonaws.com"))

however when I execute it, it returns HTML code as it should (which in this case is the external IP) but it shows that only and not after the line "Ext IP address is:" as I requested. And then I get the following exception:

Traceback (most recent call last): File "main.py", line 2, in print("Ext IP Address is:" + os.system("wget -O - -q https://checkip.amazonaws.com")) TypeError: can only concatenate str (not "int" to str

  • 1
    `os.system` does not return a string. It is possible to get the stdout from another program using `subprocess` and pipes, but it would be much simpler to just make your HTTP request using the Python `requests` library instead of a system call. – kaya3 Jan 04 '23 at 09:23
  • @kaya3 `requests` also needs to be separately installed – it's very much an acceptable tradeoff in some cases to use a system `wget` or `curl`. – AKX Jan 04 '23 at 09:54
  • @AKX There is also `urllib.request` if you cannot install a third-party library. See the linked duplicate. – kaya3 Jan 04 '23 at 10:00
  • @kaya3 Which may or may not support HTTPS properly, depending on system configuration. Again, there are situations when shelling out to an external program is fine, and getting that output was what OP was asking. – AKX Jan 04 '23 at 10:10
  • @AKX There is nothing in the question to suggest that calling out to `wget` is the best solution to the question, which is how to *"print what an HTTP(s) site has returned"*. The part about capturing output from a system call is the X in the [XY problem](https://xyproblem.info/), but if you think the question needs an answer to the X instead of the Y then I have added a duplicate link for that, too. – kaya3 Jan 04 '23 at 12:25

1 Answers1

2

os.system returns the return code of the process it runs, an integer, and you can't concatenate that to a string as you noticed.

Use subprocess.check_output to get the output of a command (and raise an exception if the command fails).

import subprocess
print(
    "Ext IP Address is:", 
    subprocess.check_output("wget -O - -q https://checkip.amazonaws.com", encoding="utf-8"),
)
AKX
  • 152,115
  • 15
  • 115
  • 172