How to do it...

Here's the code for installing a Python package using Fabric.

Listing 6.4 gives the code for installing a Python package remotely as follows:

#!/usr/bin/env python 
# Python Network Programming Cookbook, Second Edition -- Chapter - 6 
# This program is optimized for Python 2.7.12 and Python 3.5.2. 
# It may run on any other version with/without modifications. 
 
from getpass import getpass 
from fabric.api import settings, run, env, prompt 
 
 
def remote_server(): 
    env.hosts = ['127.0.0.1'] 
    env.user = prompt('Enter user name: ') 
    env.password = getpass('Enter password: ') 
     
def install_package(): 
    run("pip install yolk") 

Fabric scripts are run in a different way as compared to the normal Python scripts. All functions using the fabric library must be referred to a Python script called fabfile.py. There's no traditional __main__ directive in this script. Instead, you can define your method using the Fabric APIs and execute these methods using the command-line tool, fab. So, instead of calling python <script>.py, you can run a Fabric script, which is defined in a fabfile.py script and located under the current directory, by calling fab one_function_name another_function_name.

So, let's create a fabfile.py script as shown in the following command. For the sake of simplicity, you can create a file shortcut or link from any file to a fabfile.py script. First, delete any previously created fabfile.py file and create a shortcut to fabfile:

$ rm -rf fabfile.py
$ ln -s 6_4_install_python_package_remotely.py fabfile.py
  

If you call the fabfile now, it will produce the following output after installing the Python package, yolk, remotely as follows:

$ ln -sfn 6_4_install_python_package_remotely.py fabfile.py
$ fab remote_server install_package
Enter user name: faruq
Enter password:
[127.0.0.1] Executing task 'install_package'
[127.0.0.1] run: pip install yolk
[127.0.0.1] out: Downloading/unpacking yolk
[127.0.0.1] out:   Downloading yolk-0.4.3.tar.gz (86kB): 
[127.0.0.1] out:   Downloading yolk-0.4.3.tar.gz (86kB): 100%  86kB
[127.0.0.1] out:   Downloading yolk-0.4.3.tar.gz (86kB):           
[127.0.0.1] out:   Downloading yolk-0.4.3.tar.gz (86kB): 86kB 
downloaded
[127.0.0.1] out:   Running setup.py egg_info for package yolk
[127.0.0.1] out:     Installing yolk script to /home/faruq/env/bin
[127.0.0.1] out: Successfully installed yolk
[127.0.0.1] out: Cleaning up...
[127.0.0.1] out: 
    
Done.
Disconnecting from 127.0.0.1... done.  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.147.193