Search code examples
pythonpython-2.7apiunixredhat

Python 2.7 Windows scripts not working in Unix


I have a python script that I want to run in Redhat 6.7 OS but it is constantly failing.

**Python version: 2.7.13 (initially it had default version which I have symlink to usr/local/bin/python2.7, not sure if it has changed to 2.7 but when I type which is python in terminal it shows the location usr/local/bin/python.)

Script to be run on: OS = Redhat 6.7

Script written in: OS = Windows10 (python ver 2.7.11)

code:

import urllib
import json
url = 'https://username:pass@api.amsterdampc.com'# sample URL(tested on 'api.openweathermap.org/data/2.5/weather?q=London' too gives the same error) 
data = json.load(urllib.urlopen(url)) #should return a json data
print data

Here print data is raising "json decoder error", when i looked back into the steps I found out urllib.urlopen(url) is not at all returning the required json data instead of some ml response/empty at times.

Is there any specific changes I need to do if I run a python script in different OS isn't python a platform independent language?


Solution

  • By and large, python is reasonably platform independant. But that doesn't mean that there aren't differences between platforms. If you look through the documentation for the standard library, you will find notes that some functions or classes are only available on certain platforms. And e.g. the way multiprocessing works is also different between UNIX-like operating systems and ms-windows.

    In this case you mention that the trouble begins with the fact that urllib.urlopen doesn't return what you expect. This is probably not an issue with the Python code. I suspect it is a networking/routing/firewall issue. You would have to show the returned not-JSON data to be sure.

    As an aside, if you want to use HTML in Python, do yourself a favour and use the requests module. It is a lot more user-friendly then urllib.

    Edit 1:

    It says:

    Your request could not be processed. Request could not be handled

    This could be caused by a misconfiguration, or possibly a malformed request.

    So there are two possible causes:

    • misconfiguration
    • malformed request

    The network object returned by urllib.urlopen() has some extra methods compared to files, like info() and getcode(). Using those might yield some extra information about why the request failed.

    If you do a POST request, the information has to be formatted and encoded in a certain way. If you use requests.post, it will handle these details for you.