What is wrong with my Python code and how can I fix it?2019 Community Moderator ElectionCorrect way to try/except using Python requests module?What are metaclasses in Python?How do I copy a file in Python?How can I safely create a nested directory in Python?How can I remove a trailing newline in Python?How do I parse a string to a float or int in Python?How to get the current time in PythonHow can I make a time delay in Python?How to get the number of elements in a list in Python?How to concatenate two lists in Python?How to lowercase a string in Python?

Crossing a border with an infant of a different citizenship

What problems would a superhuman have who's skin is constantly hot?

Recommendation letter by significant other if you worked with them professionally?

Does "Until when" sound natural for native speakers?

Specifying a starting column with colortbl package and xcolor

What is Earthy controling in the ISS cupola?

Are small insurances worth it?

Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?

Is it possible that a question has only two answers?

Doubts in understanding some concepts of potential energy

What can I do if someone tampers with my SSH public key?

Confusion about Complex Continued Fraction

Outlet with 3 sets of wires

Having the player face themselves after the mid-game

Did Amazon pay $0 in taxes last year?

Why restrict private health insurance?

Am I understanding this Storm King's Thunder map wrong?

How can I get players to focus on the story aspect of D&D?

Virginia employer terminated employee and wants signing bonus returned

Source permutation

Shifting between bemols (flats) and diesis (sharps)in the key signature

Why is there an extra space when I type "ls" in the Desktop directory?

Drawing close together horizontal lines in Latex

What materials can be used to make a humanoid skin warm?



What is wrong with my Python code and how can I fix it?



2019 Community Moderator ElectionCorrect way to try/except using Python requests module?What are metaclasses in Python?How do I copy a file in Python?How can I safely create a nested directory in Python?How can I remove a trailing newline in Python?How do I parse a string to a float or int in Python?How to get the current time in PythonHow can I make a time delay in Python?How to get the number of elements in a list in Python?How to concatenate two lists in Python?How to lowercase a string in Python?










-1















Here is my code



import requests
ping = requests.get('http://example.com')
ping.status_code

if ping.status_code==200:
print ("Online")
else:
print ("Offline")


It pings http://example.com. When the website is online it successfully prints Online. when the website is offline, I want it to print Offline but instead it is showing me a huge error message ends with this line



Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd3f17372e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))


How can I fix it to successfully print Offline if the website is offline?










share|improve this question






















  • I would think you need to use a try catch, and if you catch an exception you know it is offline, otherwise it is online

    – Bentaye
    Mar 6 at 14:46











  • Possible duplicate of Correct way to try/except using Python requests module?

    – meowgoesthedog
    Mar 6 at 14:46











  • what about try/catch?

    – deathangel908
    Mar 6 at 14:46











  • You might want to wrap your call to the get function inside a try-except block to handle this case.

    – Thomas Lang
    Mar 6 at 14:46















-1















Here is my code



import requests
ping = requests.get('http://example.com')
ping.status_code

if ping.status_code==200:
print ("Online")
else:
print ("Offline")


It pings http://example.com. When the website is online it successfully prints Online. when the website is offline, I want it to print Offline but instead it is showing me a huge error message ends with this line



Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd3f17372e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))


How can I fix it to successfully print Offline if the website is offline?










share|improve this question






















  • I would think you need to use a try catch, and if you catch an exception you know it is offline, otherwise it is online

    – Bentaye
    Mar 6 at 14:46











  • Possible duplicate of Correct way to try/except using Python requests module?

    – meowgoesthedog
    Mar 6 at 14:46











  • what about try/catch?

    – deathangel908
    Mar 6 at 14:46











  • You might want to wrap your call to the get function inside a try-except block to handle this case.

    – Thomas Lang
    Mar 6 at 14:46













-1












-1








-1








Here is my code



import requests
ping = requests.get('http://example.com')
ping.status_code

if ping.status_code==200:
print ("Online")
else:
print ("Offline")


It pings http://example.com. When the website is online it successfully prints Online. when the website is offline, I want it to print Offline but instead it is showing me a huge error message ends with this line



Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd3f17372e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))


How can I fix it to successfully print Offline if the website is offline?










share|improve this question














Here is my code



import requests
ping = requests.get('http://example.com')
ping.status_code

if ping.status_code==200:
print ("Online")
else:
print ("Offline")


It pings http://example.com. When the website is online it successfully prints Online. when the website is offline, I want it to print Offline but instead it is showing me a huge error message ends with this line



Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd3f17372e8>: Failed to establish a new connection: [Errno -2] Name or service not known',))


How can I fix it to successfully print Offline if the website is offline?







python python-requests ping






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 6 at 14:44









SadieSadie

215




215












  • I would think you need to use a try catch, and if you catch an exception you know it is offline, otherwise it is online

    – Bentaye
    Mar 6 at 14:46











  • Possible duplicate of Correct way to try/except using Python requests module?

    – meowgoesthedog
    Mar 6 at 14:46











  • what about try/catch?

    – deathangel908
    Mar 6 at 14:46











  • You might want to wrap your call to the get function inside a try-except block to handle this case.

    – Thomas Lang
    Mar 6 at 14:46

















  • I would think you need to use a try catch, and if you catch an exception you know it is offline, otherwise it is online

    – Bentaye
    Mar 6 at 14:46











  • Possible duplicate of Correct way to try/except using Python requests module?

    – meowgoesthedog
    Mar 6 at 14:46











  • what about try/catch?

    – deathangel908
    Mar 6 at 14:46











  • You might want to wrap your call to the get function inside a try-except block to handle this case.

    – Thomas Lang
    Mar 6 at 14:46
















I would think you need to use a try catch, and if you catch an exception you know it is offline, otherwise it is online

– Bentaye
Mar 6 at 14:46





I would think you need to use a try catch, and if you catch an exception you know it is offline, otherwise it is online

– Bentaye
Mar 6 at 14:46













Possible duplicate of Correct way to try/except using Python requests module?

– meowgoesthedog
Mar 6 at 14:46





Possible duplicate of Correct way to try/except using Python requests module?

– meowgoesthedog
Mar 6 at 14:46













what about try/catch?

– deathangel908
Mar 6 at 14:46





what about try/catch?

– deathangel908
Mar 6 at 14:46













You might want to wrap your call to the get function inside a try-except block to handle this case.

– Thomas Lang
Mar 6 at 14:46





You might want to wrap your call to the get function inside a try-except block to handle this case.

– Thomas Lang
Mar 6 at 14:46












2 Answers
2






active

oldest

votes


















1














You're getting an error on request itself.



ping = requests.get('http://example.com')


So you don't get a status code if server didn't respond you.
If you want to check if host is down it's worth using exception handling so when request fails your script doesn't go down with an error. Following code should work.



import requests
try:
ping = requests.get('http://example.com')
print ("Online")
except:
print ("Offline")





share|improve this answer























  • Thank you. It worked!

    – Sadie
    Mar 6 at 14:58











  • always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

    – Vladimir Vishnevskyi
    Mar 6 at 15:03


















1














You can do this by modifying your code as below:



Adding try and except mechanism.



import requests
try:
ping = requests.get('http://example.com')
ping.status_code

if ping.status_code==200:
print ("Online")
else:
print ("Offline")
except requests.exceptions.ConnectionError as e:
print("Offline")





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55025775%2fwhat-is-wrong-with-my-python-code-and-how-can-i-fix-it%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You're getting an error on request itself.



    ping = requests.get('http://example.com')


    So you don't get a status code if server didn't respond you.
    If you want to check if host is down it's worth using exception handling so when request fails your script doesn't go down with an error. Following code should work.



    import requests
    try:
    ping = requests.get('http://example.com')
    print ("Online")
    except:
    print ("Offline")





    share|improve this answer























    • Thank you. It worked!

      – Sadie
      Mar 6 at 14:58











    • always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

      – Vladimir Vishnevskyi
      Mar 6 at 15:03















    1














    You're getting an error on request itself.



    ping = requests.get('http://example.com')


    So you don't get a status code if server didn't respond you.
    If you want to check if host is down it's worth using exception handling so when request fails your script doesn't go down with an error. Following code should work.



    import requests
    try:
    ping = requests.get('http://example.com')
    print ("Online")
    except:
    print ("Offline")





    share|improve this answer























    • Thank you. It worked!

      – Sadie
      Mar 6 at 14:58











    • always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

      – Vladimir Vishnevskyi
      Mar 6 at 15:03













    1












    1








    1







    You're getting an error on request itself.



    ping = requests.get('http://example.com')


    So you don't get a status code if server didn't respond you.
    If you want to check if host is down it's worth using exception handling so when request fails your script doesn't go down with an error. Following code should work.



    import requests
    try:
    ping = requests.get('http://example.com')
    print ("Online")
    except:
    print ("Offline")





    share|improve this answer













    You're getting an error on request itself.



    ping = requests.get('http://example.com')


    So you don't get a status code if server didn't respond you.
    If you want to check if host is down it's worth using exception handling so when request fails your script doesn't go down with an error. Following code should work.



    import requests
    try:
    ping = requests.get('http://example.com')
    print ("Online")
    except:
    print ("Offline")






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 6 at 14:50









    Vladimir VishnevskyiVladimir Vishnevskyi

    1526




    1526












    • Thank you. It worked!

      – Sadie
      Mar 6 at 14:58











    • always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

      – Vladimir Vishnevskyi
      Mar 6 at 15:03

















    • Thank you. It worked!

      – Sadie
      Mar 6 at 14:58











    • always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

      – Vladimir Vishnevskyi
      Mar 6 at 15:03
















    Thank you. It worked!

    – Sadie
    Mar 6 at 14:58





    Thank you. It worked!

    – Sadie
    Mar 6 at 14:58













    always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

    – Vladimir Vishnevskyi
    Mar 6 at 15:03





    always welcome. worth saying that with this particular script - if website responds with any error (like 500, 404 etc) script will still respond with "Online". So you probably should still include your status_code checks.

    – Vladimir Vishnevskyi
    Mar 6 at 15:03













    1














    You can do this by modifying your code as below:



    Adding try and except mechanism.



    import requests
    try:
    ping = requests.get('http://example.com')
    ping.status_code

    if ping.status_code==200:
    print ("Online")
    else:
    print ("Offline")
    except requests.exceptions.ConnectionError as e:
    print("Offline")





    share|improve this answer



























      1














      You can do this by modifying your code as below:



      Adding try and except mechanism.



      import requests
      try:
      ping = requests.get('http://example.com')
      ping.status_code

      if ping.status_code==200:
      print ("Online")
      else:
      print ("Offline")
      except requests.exceptions.ConnectionError as e:
      print("Offline")





      share|improve this answer

























        1












        1








        1







        You can do this by modifying your code as below:



        Adding try and except mechanism.



        import requests
        try:
        ping = requests.get('http://example.com')
        ping.status_code

        if ping.status_code==200:
        print ("Online")
        else:
        print ("Offline")
        except requests.exceptions.ConnectionError as e:
        print("Offline")





        share|improve this answer













        You can do this by modifying your code as below:



        Adding try and except mechanism.



        import requests
        try:
        ping = requests.get('http://example.com')
        ping.status_code

        if ping.status_code==200:
        print ("Online")
        else:
        print ("Offline")
        except requests.exceptions.ConnectionError as e:
        print("Offline")






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 6 at 14:55









        Devang PadhiyarDevang Padhiyar

        430119




        430119



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55025775%2fwhat-is-wrong-with-my-python-code-and-how-can-i-fix-it%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко