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

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved