The post Python 2 Vs Python 3 with Examples appeared first on PythonForBeginners.com.
]]>A lot of legacy applications are still written in Python 2. Companies facing a migration to Python 3 requires knowledge of the differences in both syntax and behavior. The purpose of this article is to outline the differences between Python 2 and Python 3. With examples, you will see how functions look syntacally the same in one version but behave completely different in another version.
The newest version of Python is 3.7 was released in 2018. The next version 3.8 is currently in development and will be released in 2024. Although Python 2.7 is still widely used. Python 3 adoption is growing quickly. In 2016, 71.9% of projects used Python 2.7, but by 2017, it had fallen to 63.7%.
Depending on what your needs are and what you want done, choose the version that will help you the most. If you can do exactly what you want with Python 3.x then great! There are however, a few downsides such as:
As long as Python 3.x is installed on your users’ computers (which in most cases are because most people reading this are developing something for themselves or on an environment they control) and you are writing things where you know none of the Python 2.x modules are needed, it is an excellent choice. Also most Linux distributions already have Python 3.x installed and nearly all have it available for end users. One caveat may be if Red Hat Enterprise Linux (through version 7) where Python 3 does exist in the EPEL repository, but some users may not be allowed to install anything from add-on locations or unsecured locations. Also some distributions are phasing Python 2 out as their former default install.
Instructors should be introducing Python 3 to new programmers, but discussing the differences in Python 2.
Refrain from starting any new development in Python 2 because as of January 2020, Python 2 will be EOL (“End of Life”) meaning all official support will cease.
The main difference is that some things will need to be imported from different places in order to handle the fact that they have different names in Python 2 and Python 3. Accordingly, the six compatibility package is a key utility for supporting Python 2 and Python 3 in a single code base.
We will discuss the major differences in each section of this article and provide examples of console screenshots in both Python 2 and Python 3.
From a library standpoint, the libraries are hugely different in Python 2 vs Python 3. Many libraries developed for Python 2 are not compatible in Python 3. The developers of libraries used in Python 3 has good standards and have enhanced the Machine Learning and Deep Learning libraries.
Integer division is the division of two numbers less the fractional part. In Python 2, you get exactly what integer division was defined to do.
In the console screenshot below, you see the division of two integers. The result in Python 2 is also an integer. The fractional part is missing.

In the console screenshot below, you see the division of two integers in Python 3. The result is a floating point number that includes the fractional part that is missing in Python 2.

If the fractional part is required in Python 2, you can specify one of the integers that you are dividing as a floating point number. That way, it forces the result to be a floating point number.
In Python 2, print is a statement that takes a number of arguments. It prints the arguments with a space in between. In Python 3, print is a function that also takes a number of arguments.
In this example, we use the print statement with three arguments. Notice that Python 2 prints the three arguments separated by a space. Next, we use the print statement with round brackets surrounding the three arguments. The result is a tuple of three elements.

In this example, we use the print function with three arguments and we get the same result as in Example 3 with Python 2. However when we want to print the tuple, we have to surround the tuple with another set of rounded brackets.

To get the same result in Python 2 as Python 3, we can use the future directive to direct the compiler to use a feature that is available in a future release.

In Python 2 when you open a text file, the open() function returns a ASCII text string. In Python 3, the same function open() returns a unicode string. Unicode strings are more versatile than ASCII strings. When it comes to storage, you have to add a “u” if you want to store ASCII strings as Unicode in Python 2.


In Python 2, there are two different kinds of objects that can be used to represent a string. These are ‘str’ and ‘unicode’. Instances of ‘str’ are byte representations whereas with unicode, are 16 or 32-bit integers. Unicode strings can be converted to byte strings with the encode() function.
In Python 3, there are also two different kinds of objects that can be used to represent a string. These are ‘str’ and ‘bytes’. The ‘str’ corresponds to the ‘unicode’ type in Python 2. You can declare a variable as ‘str’ and store a string in it without prepending it with a ‘u’ because it is default now. ‘Bytes’ corresponds to the ‘str’ type in Python 2. It is a binary serialization format represented by a sequence of 8-bits integers that is great for sending it across the internet or for storing on the filesystem.
Error handling in Python consists of raising exceptions and providing exception handlers. The difference in Python 2 vs Python 3 are mainly syntactical. Let’s look at a few examples.
In the console screenshot below, we try to raise error in both formats and it works.

In the console screenshot below, raising error does not work in Python 3 as it was in Python 2.

With exception handlers, the syntax has changed slightly in Python 3.
In the console screenshot below, we specify a try block with an exception handler. We purposely cause an error by specifying an undefined name in the ‘try’.

In the console screenshot below, we specify the same code as the previous example in Python 2. Notice the new syntax in Python 3, requiring us to use the word ‘as’.

In Python 2, it was possible to compare unorderable types such as a list with a string.

New in Python 3, a TypeError is raised if you try to compare a list with a string.

In Python 2, there is the range() function and the xrange() function. The range() function will return a list of numbers whereas the xrange() function will return an object.
In Python 3, there is only the range() function and no xrange() function. The reason why there is no xrange() function is because the range() function behaves like the xrange() function in Python 2. In other words, the range() function returns the range object.
In the console screenshot below, we see that the range() function returns a list containing 5 elements because we passed ‘5’ as an argument. When we use xrange(), we get an object back instead.

As you can see from the console screenshot below, entering the range() function with ‘5’ as an argument causes an object to be returned. However when we try to use the xrange() function, we see that Python 3 does not like it because it is undefined.

In Python 2, there were a number of functions that return lists. In Python 3, a change was made to return iterable objects instead of lists. This includes the following functions:
If you’re planning Python 3 support for your Python 2 code then you might want to add the __future__ module. For example, integer division had changed from Python 2 to 3 but if you want your Python 2 code to behave like Python 3, all you have to do is to add this line:
“from __future__ import division”
Now in your Python 2 code, dividing two integers will result in a floating point number.
As you can see below, when we divide 2 / 3, we get 0 which is type integer. But after we import division from the __future__ module, 2 / 3 returned type floating point number.

There are other things you can specify to make your future migrations easier. They include:
The post Python 2 Vs Python 3 with Examples appeared first on PythonForBeginners.com.
]]>The post How To Run Your Python Scripts appeared first on PythonForBeginners.com.
]]>In this blog post, we will take a look at 7 ways to execute Python code and scripts. No matter what your operating system is, your Python environment or the location of your code – we will show you how to execute that piece of code!
You can run a Python script from:
To start an interactive session for Python code, simply open your Terminal or Command line and type in Python(or Python 3 depending on your Python version). And, as soon as you hit enter, you’ll be in the interactive mode.
Here’s how you enter interactive mode in Windows, Linux and MacOS.
Open up your Terminal.
It should look something like
$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
Enter the Python script interactive mode after pressing “Enter”.
Launching interactive Python script mode on Mac OS is pretty similar to Linux. The image below shows the interactive mode on Mac OS.

On Windows, go to your Command Prompt and write “python”. Once you hit enter you should see something like this:

With interactive Python script mode, you can write code snippets and execute them to see if they give desired output or whether they fail.
Take an example of the for loop below.

Our code snippet was written to print everything including 0 and upto 5. So, what you see after print(i) is the output here.
To exit interactive Python script mode, write the following:
>>>exit()
And, hit Enter. You should be back to the command line screen that you started with initially.
There are other ways to exit the interactive Python script mode too. With Linux you can simply to Ctrl + D and on Windows you need to press Ctrl + Z + Enter to exit.
Note that when you exit interactive mode, your Python scripts won’t be saved to a local file.
A nice way to visualize what happens when you execute a Python script is by using the diagram below. The block represents a Python script (or function) we wrote, and each block within it, represents a line of code.

When you run this Python script, Python interpreter goes from top to bottom executing each line.
And, that’s how Python interpreter executes a Python script.
But that’s not it! There’s a lot more that happens.
Step 1: Your script or .py file is compiled and a binary format is generated. This new format is in either .pyc or .pyo.

Step 2: The binary file generated, is now read by the interpreter to execute instructions.
Think of them as a bunch of instructions that leads to the final outcome.
There are some benefits of inspecting bytecode. And, if you aim to turn yourself into a pro level Pythonista, you may want to learn and understand bytecode to write highly optimized Python scripts.
You can also use it to understand and guide your Python script’s design decisions. You can look at certain factors and understand why some functions/data structures are faster than others.
To run a Python script using command line, you need to first save your code as a local file.
Let’s take the case of our local Python file again. If you were to save it to a local .py file named python_script.py.
There are many ways to do that:
Saving a Python script from a code editor is pretty easy. Basically as simple as saving a text file.
But, to do it via Command line, there are a couple of steps involved.
First, head to your command line, and change your working directory to where you wish to save the Python script.
Once you are in the right directory, execute the following command in Terminal:
$ sudo nano python_script.py
Once you hit enter, you’ll get into a command line interface that looks something like this:

Now, you can write a Python code here and easily run it using command line.
Python scripts can be run using Python command over a command line interface. Make sure you specify the path to the script or have the same working directory. To execute your Python script(python_script.py) open command line and write python3 python_script.py
Replace python3 with python if your Python version is Python2.x.
Here’s what we saved in our python_script.py
for i in range(0,5):
print(i)
And, the output on your command line looks something like this

Let’s say, we want to save the output of the Python code which is 0, 1, 2, 3, 4 – we use something called a pipe operator.
In our case, all we have to do is:
$python python_script.py > newfile.txt
And, a file named “newfile.txt” would be created with our output saved in it.
There are more than 4 ways to run a Python script interactively. And, in the next few sections we will see all major ways to execute Python scripts.
We all use import module to load scripts and libraries extremely frequently. You can write your own Python script(let’s say code1.py) and import it into another code without writing the whole code in the new script again.
Here’s how you can import code1.py in your new Python script.
>>> import code1
But, doing so would mean that you import everything that’s in code1.py to your Python code. That isn’t an issue till you start working in situations where your code has to be well optimized for performance, scalability and maintainability.
So, let’s say, we had a small function inside code1 that draws a beautiful chart e.g. chart_code1(). And, that function is the only reason why we wish to import the entire code1.py script. Rather than having to call the entire Python script, we can simply call the function instead.
Here’s how you would typically do it
>>> from code1 import chart_code1
And, you should be able to use chart_code1 in your new Python script as if it were present in your current Python code.
Next, let’s look at other ways to import Python code.
import_module() of importlib allows you to import and execute other Python scripts.
The way it works is pretty simple. For our Python script code1.py, all we have to do is:
import importlib
import.import_module(‘code1’)
There’s no need to add .py in import_module().
Let’s go through a case where we have complex directory structures and we wish to use importlib. Directory structure of the Python code we want to run is below:
level1
|
+ – __init__.py
– level2
|
+ – __init__.py
– level3.py
In this case if you think you can do importlib.import_module(“level3”), you’ll get an error. This is called relative import, and the way you do it is by using a relative name with anchor explicit.
So, to run Python script level3.py, you can either do
importlib.import_module(“.level3”, “level1.level”)
or you can do
importlib.import_module(“level1.level2.level3”).
Runpy module locates and executes a Python script without importing it. Usage is pretty simple as you can easily call the module name inside of run_module().
To execute our code1.py module using runpy. Here’s what we will do.
>>> import runpy
>>> runpy.run_module(mod_name=”code1”)
We are going to take a look at exec() function to execute Python scripts dynamically. In Python 2, exec function was actually a statement.
Here’s how it helps you execute a Python code dynamically in case of a string.
>>> print_the_string = ‘print(“Dynamic Code Was Executed”)’
>>> exec(print_the_string)
Dynamic Code Was Executed
However, using exec() should be a last resort. As it is slow and unpredictable, try to see if there are any other better alternatives available.
To run Python script using a Python Text Editor you can use the default “run” command or use hot keys like Function + F5 or simply F5(depending on your OS).
Here’s an example of Python script being executed in IDLE.

Source: pitt.edu
However, note that you do not control the virtual environment like how you typically would from a command line interface execution.
That’s where IDEs and Advanced text editors are far better than Code Editors.
When it comes to executing scripts from an IDE, you can not only run your Python code, but also debug it and select the Python environment you would like to run it on.
While the IDE’s UI interface may vary, the process would be pretty much similar to save, run and edit a code.
What if there was a way to run a Python script just by double clicking on it? You can actually do that by creating executable files of your code. For example, in the case of Windows OS, you can simply create a .exe extension of your Python script and run it by double clicking on it.
Although we haven’t already stated this, but, if you go back up and read, you’ll notice that you can:
That’s it!
The post How To Run Your Python Scripts appeared first on PythonForBeginners.com.
]]>The post The 5 Best Python IDE’s and Code Editors for 2019 appeared first on PythonForBeginners.com.
]]>In this article, we will take a look at the top 5 Python IDEs and 5 Python text editors.
Based on your field, price and features – you’ll get to see which Python IDEs and Code Editors will be best for you.
Confused between an IDE like Eclipse, or if you should for something as simple as Sublime Text? We have got everything covered!
| IDE | Cost | OS Supported | Size | Size(in MB) | Languages Supported | iPython Notebook |
| PyCharm | $199/year | Windows, MacOS, Linux | Big | 150-176 MB | Python, Javascript, Coffescript, XML, HTML/XHTML, YAML, CSS, Saas, Stylus | No |
| Spyder | Free | Windows, MacOS, Linux | Big | 361-427MB | Python | Yes |
| PyDev | Free | Windows, MacOS, Linux | Big | 300MB | Python, C++, Coffeescript, HTML, Javascript, CSS | Yes |
| IDLE | Free | Windows, MacOS, Linux | Small | 15.6 MB | Python | No |
| Wing | Free, Paid | Windows, MacOS, Linux | Big | 400 MB | Python | Yes |
We will now get into the depths of each of these IDEs and Text Editors. And, we will look into factors that will help you decide which one is the best IDE for Python.
Price: $199 per year per developer
Operating Systems Supported: Windows, MacOS and Linux Distros.

Source: Jetbrains
PyCharm, an IDE developed and maintained by JetBrains is one of the most popular Python IDE. In a survey done by JetBrains, more than 20% of developers mentioned Pycharm as their preferred IDE.
As an IDE, PyCharm does much more than just allowing you to import libraries and write code. It is a professional grade IDE that allows Python developers to write production grade and maintainable code.
Pros
Cons :
Price: Free
Operating Systems Supported: Windows, MacOS, Linux

Source: Spyder.com
SPYDER is actually an acronym that stands for Scientific PYthon Development EnviRonment. This IDE is mainly used by the Scientific Python community.
Tools and libraries like Numpy, Scipy, Matplotlib, etc are in-built with this Python IDE. Powerful features specifically built for the scientific programming makes Spyder a preferred IDE. It is also one of the best alternatives for Scientific programmers outside of Matlab.
Pros
Cons
Price: Free
Operating Systems Supported: Windows, MacOS, Linux

Source: Pydev.org
PyDev started as an IDE that primarily worked with Eclipse, allowing Pythonista’s write code on Eclipse. But, no it has expanded beyond Eclipse and now can also be integrated with Visual Studio Code.
Although free, PyDev integration with VS Code costs $40 after a free trial of 1 month.
Pros
Cons
Price: Free
Operating Systems Supported: Windows, MacOS, Linux

Python IDLE comes by default in the Python Bundle once you download Python. This is a great IDE for entry level Python programmers as it is pretty much hassle free to set up on all OSes.
It is absolutely free to use. But, it isn’t good enough to create advanced level production grade Python code.
Pros:
Cons:
Price: $45 for Educators, $99 per user for professional license
Operating Systems Supported: Windows, MacOS, Linux

Wing is a faster, stable and extremely light Python IDE, and if often compared a lot with PyCharm. From affordable subscription options to numerous features, this is the IDE which every PyCharm user should check out.
Pros:
Cons:
Python Code Editors unlike an IDE are just simply programs that allows you to write code. With these code editors, you can import libraries, frameworks and write code.
Even though we went through those IDEs, Python code editors have their own place. Without Code editors in Python, most developers wouldn’t learn or understand syntax and snippets.
So, let’s see what top Python code editors are.
Cost: $80
Operating Systems Supported: Windows, Linux and MacOS
Sublime Screenshot

Source: Sublimetext.com
Sublime Text is best in class Code Editor that’s extremely fast and allows developers to write their own plugins. With numerous features like multi-line editing, block editing, regex search, etc – it’s definitely one of the top code editor for Python developers.
Cost: Free
Operating Systems Supported: Windows, Linux and MacOS
Atom was one of the earliest code editors that was released. It had it’s traction, but doesn’t holds a significant share amongst other code editors in the Python community anymore. The advantage that most code editors bring over IDEs is that code editors are much faster. But, Atom is much slower than most other code editors.
Cost: Free
Operating Systems Supported: Windows, Linux and MacOS
Vim Screenshot

Source: Spacevim.org
Vim for most of the part is a command line interface code editor, but it can also work as a standalone application. Among other things, VIM is fast, cross platform and extremely performant.
While Vim has its upsides on using it as a text editor, it certainly isn’t the first choice for beginners. Learning Vim while learning Python is like learning two things at the same time. If you’re a seasoned developer, you’ll find yourself way more productive with Vim than what an entry level Python developer would.
Cost: Free
Operating Systems Supported: Windows, Linux and MacOS
Visual Studio Screeshot

Source: Visualstudio.com
Visual Studio(VS) Code was developed by Microsoft and released in the year 2015. It is available to download for free.
VS Code editor supports Python snippets, syntax highlighting, brace matching and code folding.
Cost: Free
Operating Systems Supported: Windows, Linux and MacOS
Jupyter Screenshot

Source: Jupyter.org
Jupyter Notebooks are scientific computing and data professional’s favourite Python editor. Jupyter is best if your work involves data exploration, research and presentation.
You can save your notebooks in JSON format or export your results in PDF and HTML formats.
Python Code editors are simple interfaces that allow you to write programs or modules of your Python programs. Code editors are pretty limited in terms of what they can do apart from writing programs and highlighting syntax.
IDEs on the other hand allow you to do everything – writing code, debugging, version control and everything else that makes your work professional grade. From writing code to integration of your work with CI/CD process – an IDE can help you with everything.
Well, it depends on your use case. Ideally, each IDE has its own pros and cons. For example, If you need remote deployment as a feature consider PyCharm. But, if you are a data professional, you may want to explore Spyder’s features.
The post The 5 Best Python IDE’s and Code Editors for 2019 appeared first on PythonForBeginners.com.
]]>The post List of Python API’s appeared first on PythonForBeginners.com.
]]>Many Internet companies, such as Facebook, Google, and Twitter provides Application Programming Interfaces (or API’s) that you can use to build your own applications. An API is a set of programming instructions and standards for accessing web based software applications. A wrapper is an API client, that are commonly used to wrap the API into easy to use functions by doing the API calls itself. This page provides you with a list of python API’s, but also a link to its Python wrapper.
Amazon Web Services is a collection of remote computing services that together make up a cloud computing platform, offered over the Internet by Amazon.com
Bing is a search engine that brings together the best of search and people in your social networks to help you spend less time searching and more time doing.
URL shortening and bookmarking service
Blog-publishing service
Online file sharing and Cloud content management service for enterprise companies.
Keep, share, and discover the best of the Web using Delicious, the world’s leading social bookmarking service.
Free service that lets you bring your photos, docs, and videos anywhere and share them easily
Facebook is an online social networking service.
Foursquare is a location-based social networking website for mobile devices, such as smartphones
Online auction and shopping website
Image hosting and video hosting website
A Geocoding Toolbox for Python. Official git repo.
Google Maps is a web mapping service application and technology provided by Google
Simple Image Sharer
Search engine for jobs
Online photo-sharing, video-sharing and social networking service that enables its users to take pictures and videos
The world’s largest online music catalogue, powered by your scrobbles.
World’s Largest Professional Network
Cloud- based log management service
On-demand Internet streaming media
IT alert monitoring
Cloud- based log management service
Pinterest is a pinboard-style photo-sharing website that allows users to create and manage theme-based image collections such as events, interests, and hobbies.
A social news and entertainment website where registered users submit content in the form of either a link or a text post
Film review aggregator
Share your sounds
Commercial music streaming service
Technorati is an Internet search engine for searching blogs.
Twitter is an online social networking service and microblogging service that enables its users to send and read text-based messages of up to 140 characters, known as tweets
Tumblr, stylized in their logo as tumblr., is a microblogging platform and social networking website
Wikipedia is a free, web-based, collaborative, multilingual encyclopedia project supported by the non-profit Wikimedia Foundation.
Web portal, search engine Yahoo! Search, and related services, including Yahoo! Directory, Yahoo! Mail, Yahoo!
Local search website
YouTube is a video-sharing website
Is a social news website focusing on computer science and entrepreneurship.
Wunderground
How To Access Various Web Services in Python
The post List of Python API’s appeared first on PythonForBeginners.com.
]]>The post Development Environment in Python appeared first on PythonForBeginners.com.
]]>
Some of the steps needed to setup a development environment includes:
Operating system - e.g Linux / Mac
Project structure - project structure
Virtualenv - isolated installation of the project
Pip - a tool for installing and managing Python packages
Git - source control
Webserver - where we can manage our applications
Fabric - automated deployment
Create an empty top-level directory for our new project.
helloflask/
-static/
-css
-font
-img
-js
-templates
-routes.py
Then cd into the directory
cd helloflask
Many developers uses virtualenv (virtual environment) on their computer, which
is useful when you want to run several applications on the same computer.
Virtualenv will manage all dependencies and enables multiple side-by-side
installations of Python, one for each project.
It doesn't install separate copies of Python, but provides a way to keep
different project environments isolated.
If we want to run more than one (which is often the case) web application on
that host, then you should really install 'Virtualenv'.
If you don't use virtualenv , you will have it all globally installed.
Download and Install Virtualenv into a virtual environment
# If you are using Linux/Mac: sudo pip install virtualenv
Navigate to the directory you want your project in:
$ virtualenv venv # this creates the folder venv $ source venv/bin/activate # start working on your new project (venv)$ pip install Flask # installs Flask
For more information on how to download install virtualenv, see this article.
PIP is a tool for installing and managing Python packages.
PIP comes with a command-line interface, which makes installing Python software
packages as easy as issuing one command
pip install some-package-name
Users can also easily implement the package's subsequent removal
pip uninstall some-package-name
Pip has a feature to manage full lists of packages and corresponding version
numbers through a "requirements" file.
This permits the efficient re-creation of an entire group of packages in a
separate environment (e.g. another computer) or virtual environment.
This can be achieved with a properly formatted requirements.txt file
pip install -r requirements.txt
This makes dependencies easy, you can create a requirements file based on a set of
packages installed in your virtual environment.
pip freeze > requirements.txt
When deploying to a server it is important to register which requirements we need.
The requirements file can be done automatically using the freeze command for pip.
This command will generate a plain text file that contains the names of the
required Python packages and their versions, for example Flask==0.9
To do this we freeze the installed packages and store this setup in a
requirements.txt file
$ cat requirements.txt Flask==0.9 Jinja2==2.6 Werkzeug==0.8.3
The requirements file can be used to rebuild a virtual environment or to deploy a
virtual environment into the machine.
Now that we have a clean Flask environment to work in, we'll create our simple
application.
The simplest Flask App looks something like this:
Put this code into the file and name it 'hello.py'
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
Now it's time to create the repository on Github. The purpose of setting up a
Github project, is so that we can push files from our local computer to Github
and then pull the files from Github to our web server.
Create a new Github account and create a new project (helloflask)
By using a versioning system, we can store all our files in a Github repository.
The first thing you need to do on your local computer is to install and setup git.
To install git, simple run:
sudo apt-get install git
Put in your username and email into the .gitconfig file (~/.gitconfig)
git config --global user.name "pythonforbeginners" git config --global user.email [email protected]
Since our current directory contains a lof of extra files, we'll want to
configure our repository to ignore these files with a .gitignore file:
venv
*.pyc
Next, we’ll create a new git repository and save our changes.
# Initialize Git in our project directory git init
This creates a git repository in the current directory.
Add all of our files to our initial commit
git add .
Check the status, this will list all files
git status
With the files added to the Git index, we can now commit them to our repo:
$ git commit -m 'Initial commit'
Now we have created a local Git repository for our application (local) files.
Setup Github as the origin
git remote add origin [email protected]:USERNAME/helloflask.git git push -u origin master
Now its time to start up the web server and do some configuration.
If you want to use Apache as a web server, you can install it like this:
sudo apt-get install apache2
Configure a virtual host (vhost) in /etc/apache2/sites-available/siteX
Install virtualenv just like you did on your local computer.
Set up the environment for the website, here I use /var/www
Cd into that folder and clone the project that you setup on Github, by typing:
git clone [email protected]:USERNAME/helloflask.git
Initialize and activate your virtualenv
virtualenv helloflask cd helloflask source bin/activate
Install dependencies
pip install -r requirements.txt
Fabric is used for deployment. You can of course always manually upload the code
and restart the web server to reflect the configuration changes.
Using fabric in a development environment, where you have multiple servers with
multiple people pushing the code multiple times per day, this can be incredible
very useful.
Fabric can configure the system, execute commands on local/remote server, deploy
your application, do rollbacks etc.
It does that by using its command-line utility that will run a fabfile containing
instructions on how to deploy to a server.
A common practice when developing is to use Git to deploy and Fabric to automate
it.
pip install fabric
Fabric expects a fabfile named fabfile.py which defines all of the actions we can
take.
The fabfile.py should be in your project's root directory.
I like to use this script that asks the server to pull from the git repository
and restart apache. [source]
from fabric.api import * # import fabrics API functions
env.hosts = ['[email protected]:22'] # add the remote server information
def pushpull():
local('git push') # runs the command on the local environment
run('cd /path/to/project/; git pull') # runs the command on the remote environment
#Run it with: $ fab pushpull
For more information on how to use fabric in a development environment, please
refer to this article.
The post Development Environment in Python appeared first on PythonForBeginners.com.
]]>