Installing Python 3 on Mac OS X. Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable. For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8. How to Install Python 2. Installing Python 2 is a snap, and unlike in years past, the installer will even set the path variable for you (something we’ll be getting into a bit later). Download and run the installer, select “Install for all users,” and then click “Next.”.
Python doesn’t come prepackaged with Windows, but that doesn’t mean Windows users won’t find the flexible programming language useful. It’s not quite a simple as installing the newest version however, so let’s make sure you get the right tools for the task at hand.First released in 1991, Python is a popular high-level programming language used for general purpose programming. Thanks to a design philosophy that emphasizes readability it has long been a favorite of hobby coders and serious programmers alike.
Not only is it an easy language (comparatively speaking, that is) to pick up but you’ll find thousands of projects online that require you have Python installed to use the program. Which Version Do You Need?Unfortunately, there was a significant update to Python several years ago that created a big split between Python versions. This can make things a bit confusing to newcomers, but don’t worry. We’ll walk you through installing both major versionsWhen you visit the, you’ll immediately see the division. Right at the top, square and center, the repository asks if you want the latest release of Python 2 or Python 3 (2.7.13 and 3.6.1, respectively, as of this tutorial).RELATED:Newer is better, right? Maybe so, maybe not. The version you want depends on your end goal. Let’s say, for example, that you read and are excited to add cool stuff to your worlds.
That project is coded in Python and requires Python 2.7—you can’t run the MCDungeon project with Python 3.6. In fact, if you’re exploring hobby projects like MCDungeon, you’ll find that nearly all of them use 2.7. If your goal is to get some project that ends in a “.py” extension up and running, then there’s a very, very good chance you’ll need 2.7 for it.On the other hand, if you’re looking to actually learn Python, we recommend installing both versions side by side (which you can do with zero risk and only a tiny bit of setup hassle). This lets you work with the newest version of the language, but also run older Python scripts (and test backwards compatibility for newer projects).
Comparing the two versions is an article unto itself, though, so we’ll defer to the Python project wiki where you can read their.You can download just Python 2 or Python 3 if you’re sure you only need a particular version. We’re going the distance today and will be installing both of them, so we recommend you download both versions and do the same. Under the main entry for both versions you’ll see an “x86-64” installer, as seen below.RELATED:This installer will install the appropriate 32-bit or 64-bit version on your computer automatically (here’s if you want to know more about the differences between the two). How to Install Python 2Installing Python 2 is a snap, and unlike in years past, the installer will even set the path variable for you (something we’ll be getting into a bit later)., select “Install for all users,” and then click “Next.”On the directory selection screen, leave the directory as “Python27” and click “Next.”On the customization screen, scroll down, click “Add python.exe to Path,” and then select “Will be installed on local hard drive.” When you’re done, click “Next.”You don’t have to make any more decisions after this point.
Just click through the wizard to complete the installation. When the installation is finished, you can confirm the installation by opening up Command Prompt and typing the following command: python -VSuccess! If all you need is Python 2.7 for some project or another, you can stop right here. It’s installed, the path variable is set, and you’re off to the races.
How to Install Python 3If you want to learn the newest version of Python, you’ll need to install Python 3. You can install it alongside Python 2.7 with no problems, so go ahead and now.On the first screen, enable the “Add Python 3.6 to PATH” option and then click “Install Now.”Next, you have a decision to make. Clicking the “Disable path length limit” option removes the limitation on the MAXPATH variable. This change won’t break anything, but will allow Python to use long path names. Since many Python programmers are working in Linux and other.nix systems where path name length isn’t an issue, turning this on in advance can help smooth over any path-related issues you might have while working in Windows.RELATED:We recommend go ahead and selecting this option. If you know you don’t want to disable the path length limit, you can just click “Close” to finish the installation. And, if you want to read more about the issue before committing to the change,.If you’re only installing Python 3, you can use the same command line trick of typing python -v that we used above to check that it is installed correctly and the path variable is set.
If you’re installing both versions, however, you need to make the quick tweak found in the following section. Adjust System Variables So You Can Access Both Python Versions From the Command LineThis section of the tutorial is completely optional, but will allow you to quickly access both versions of Python from the command line. After installing both versions of Python, you may have noticed a little quirk. Even though we enabled the system path for both Python installations, typing “python” at the command prompt only points you to Python 2.7.The reason for this is simple: the variable (whether automatically adjusted by an installer or manually tweaked) simply points at a directory, and every executable in that directory becomes a command line command. If there are two directories listed and both have a “python.exe” file in them, whichever directory is higher in the list of variables gets used. And, if there is a variable set for the system and the user, the system path takes precedence over the user path.The latter is exactly what’s happening in this case: the Python 2 installer edited the system wide variable and the Python 3 installer added a user level variable—and we can confirm this by looking at the Windows’ environment variables.Hit Start, type “advanced system settings,” and then select the “View advanced system settings” option.
In the “System Properties” window that opens, on the “Advanced” tab, click the “Environment Variables” button.Here, you can see Python 3 listed in the “User variables” section and Python 2 listed in the “System variables” section.There are a few ways you can remedy this situation. The simplest (albeit the one with the least functionality) is to just remove the entry for the version of Python you plan on using the least. While that’s simple, it’s also not very much fun. Instead we can make another change that will give us access to “python” for Python 2 and “python3” for Python 3.To do this, fire up File Manager and head to the folder where you installed Python 3 ( C:UsersusernameAppDataLocalProgramsPythonPython36 by default). Make a copy of the “python.exe” file, and rename that copy ( not the original) to “python3.exe”.Open a new command prompt (the environmental variables refresh with each new command prompt you open), and type “python3 –version”.Boom! You can now use the “python” command at the Command Prompt when you want to use Python 2.7 and the “python3” command when you want to use Python 3.RELATED:If, for whatever reason, you don’t find this a satisfactory solution, you can always reorder the environmental variables. Be sure to first if you’re not comfortable editing those variables.Please note, however, that regardless of which method you use it is important to leave the original python.exe intact as the applications in the /scripts/ subdirectory for both versions of Python rely on that filename and will fail if it is missing.After a little installing and a little tweaking, you have both versions installed and you’re ready for whatever Python project you want to tackle.
A tutorial on Basic Authentication, with examples in Python.urllib.request is a Python module for fetching URLs(Uniform Resource Locators). It offers a very simple interface, in the form ofthe urlopen function. This is capable of fetching URLs using a variety ofdifferent protocols. It also offers a slightly more complex interface forhandling common situations - like basic authentication, cookies, proxies and soon.
These are provided by objects called handlers and openers.urllib.request supports fetching URLs for many “URL schemes” (identified by the stringbefore the ':' in URL - for example 'ftp' is the URL scheme of'ftp://python.org/') using their associated network protocols (e.g. FTP, HTTP).This tutorial focuses on the most common case, HTTP.For straightforward situations urlopen is very easy to use.
But as soon as youencounter errors or non-trivial cases when opening HTTP URLs, you will need someunderstanding of the HyperText Transfer Protocol. The most comprehensive andauthoritative reference to HTTP is. This is a technical document andnot intended to be easy to read.
This HOWTO aims to illustrate using urllib,with enough detail about HTTP to help you through. It is not intended to replacethe docs, but is supplementary to them. Import shutil import tempfile import urllib.request with urllib. Urlopen ( ') as response: with tempfile.
NamedTemporaryFile ( delete = False ) as tmpfile: shutil. Copyfileobj ( response, tmpfile ) with open ( tmpfile. Name ) as html: passMany uses of urllib will be that simple (note that instead of an ‘http:’ URL wecould have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s thepurpose of this tutorial to explain the more complicated cases, concentrating onHTTP.HTTP is based on requests and responses - the client makes requests and serverssend responses. Urllib.request mirrors this with a Request object which representsthe HTTP request you are making. In its simplest form you create a Requestobject that specifies the URL you want to fetch. Calling urlopen with thisRequest object returns a response object for the URL requested.
This response isa file-like object, which means you can for example call.read on theresponse. DataSometimes you want to send data to a URL (often the URL will refer to a CGI(Common Gateway Interface) script or other web application). With HTTP,this is often done using what’s known as a POST request. This is often whatyour browser does when you submit a HTML form that you filled in on the web. Notall POSTs have to come from forms: you can use a POST to transmit arbitrary datato your own application.
In the common case of HTML forms, the data needs to beencoded in a standard way, and then passed to the Request object as the dataargument. The encoding is done using a function from thelibrary. HeadersWe’ll discuss here one particular HTTP header, to illustrate how to add headersto your HTTP request.Some websites dislike being browsed by programs, or send different versionsto different browsers. By default urllib identifies itself asPython-urllib/x.y (where x and y are the major and minor versionnumbers of the Python release,e.g. Python-urllib/2.5), which may confuse the site, or just plainnot work. The way a browser identifies itself is through theUser-Agent header. When you create a Request object you canpass a dictionary of headers in.
The following example makes the samerequest as above, but identifies itself as a version of InternetExplorer. HTTPErrorEvery HTTP response from the server contains a numeric “status code”. Sometimesthe status code indicates that the server is unable to fulfil the request. Thedefault handlers will handle some of these responses for you (for example, ifthe response is a “redirection” that requests the client fetch the document froma different URL, urllib will handle that for you). For those it can’t handle,urlopen will raise an HTTPError.
Typical errors include ‘404’ (page notfound), ‘403’ (request forbidden), and ‘401’ (authentication required).See section 10 of for a reference on all the HTTP error codes.The HTTPError instance raised will have an integer ‘code’ attribute, whichcorresponds to the error sent by the server. Info and geturlThe response returned by urlopen (or the HTTPError instance) has twouseful methods info and geturl and is defined in the module.geturl - this returns the real URL of the page fetched. This is usefulbecause urlopen (or the opener object used) may have followed aredirect. The URL of the page fetched may not be the same as the URL requested.info - this returns a dictionary-like object that describes the pagefetched, particularly the headers sent by the server. It is currently anhttp.client.HTTPMessage instance.Typical headers include ‘Content-length’, ‘Content-type’, and so on. See thefor a useful listing of HTTP headers with brief explanations of their meaningand use. Openers and HandlersWhen you fetch a URL you use an opener (an instance of the perhapsconfusingly-named ).
Normally we have been usingthe default opener - via urlopen - but you can create customopeners. Openers use handlers. All the “heavy lifting” is done by thehandlers. WWW-Authenticate: Basic realm='cPanel Users'The client should then retry the request with the appropriate name and passwordfor the realm included as a header in the request.
This is ‘basicauthentication’. In order to simplify this process we can create an instance ofHTTPBasicAuthHandler and an opener to use this handler.The HTTPBasicAuthHandler uses an object called a password manager to handlethe mapping of URLs and realms to passwords and usernames. If you know what therealm is (from the authentication header sent by the server), then you can use aHTTPPasswordMgr. Frequently one doesn’t care what the realm is. In thatcase, it is convenient to use HTTPPasswordMgrWithDefaultRealm.
This allowsyou to specify a default username and password for a URL. This will be suppliedin the absence of you providing an alternative combination for a specificrealm. We indicate this by providing None as the realm argument to theaddpassword method.The top-level URL is the first URL that requires authentication. URLs “deeper”than the URL you pass to.addpassword will also match. # create a password manager passwordmgr = urllib. HTTPPasswordMgrWithDefaultRealm # Add the username and password. # If we knew the realm, we could use it instead of None.
Toplevelurl = 'passwordmgr. Addpassword ( None, toplevelurl, username, password ) handler = urllib. HTTPBasicAuthHandler ( passwordmgr ) # create 'opener' (OpenerDirector instance) opener = urllib.
Buildopener ( handler ) # use the opener to fetch a URL opener. Open ( aurl ) # Install the opener. # Now all calls to urllib.request.urlopen use our opener.
Installopener ( opener ). NoteIn the above example we only supplied our HTTPBasicAuthHandler tobuildopener. By default openers have the handlers for normal situations– ProxyHandler (if a proxy setting such as an httpproxyenvironment variable is set), UnknownHandler, HTTPHandler,HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler,FileHandler, DataHandler, HTTPErrorProcessor.toplevelurl is in fact either a full URL (including the ‘http:’ schemecomponent and the hostname and optionally the port number)e.g. 'or an “authority” (i.e. The hostname,optionally including the port number) e.g. 'example.com' or 'example.com:8080'(the latter example includes a port number). The authority, if present, mustNOT contain the “userinfo” component - for example 'joe:[email protected]' isnot correct.
Sockets and LayersThe Python support for fetching resources from the web is layered. Urllib usesthe library, which in turn uses the socket library.As of Python 2.3 you can specify how long a socket should wait for a responsebefore timing out.
This can be useful in applications which have to fetch webpages. By default the socket module has no timeout and can hang. Currently,the socket timeout is not exposed at the http.client or urllib.request levels.However, you can set the default timeout globally for all sockets using.
FootnotesThis document was reviewed and revised by John Lee.Google for example.Browser sniffing is a very bad practice for website design - buildingsites using web standards is much more sensible. Unfortunately a lot ofsites still send different versions to different browsers.The user agent for MSIE 6 is‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;.NET CLR 1.1.4322)’For details of more HTTP request headers, see.In my case I have to use a proxy to access the internet at work. If youattempt to fetch localhost URLs through this proxy it blocks them.
IEis set to use the proxy, which urllib picks up on. In order to testscripts with a localhost server, I have to prevent urllib from usingthe proxy.urllib opener for SSL proxy (CONNECT method):.
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
January 2023
Categories |