Modules In Python Category Page - PythonForBeginners.com https://www.pythonforbeginners.com Learn By Example Sat, 17 Jun 2023 15:29:08 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.12 https://www.pythonforbeginners.com/wp-content/uploads/2020/05/cropped-pfb_icon-32x32.png Modules In Python Category Page - PythonForBeginners.com https://www.pythonforbeginners.com 32 32 201782279 How to use Python SimpleHTTPServer https://www.pythonforbeginners.com/modules-in-python/how-to-use-simplehttpserver https://www.pythonforbeginners.com/modules-in-python/how-to-use-simplehttpserver#comments Wed, 03 Jul 2013 14:28:20 +0000 https://www.pythonforbeginners.com/?p=5764 Python provides us with various modules to work on different tasks. If you want to create a simple web server in Python to serve files, you can use the Python SimpleHTTPServer module. In this article, we will discuss the basics of Python SimpleHTTPServer and how it works. What is Python SimpleHTTPServer? The SimpleHTTPServer module that […]

The post How to use Python SimpleHTTPServer appeared first on PythonForBeginners.com.

]]>
Python provides us with various modules to work on different tasks. If you want to create a simple web server in Python to serve files, you can use the Python SimpleHTTPServer module. In this article, we will discuss the basics of Python SimpleHTTPServer and how it works.

What is Python SimpleHTTPServer?

The SimpleHTTPServer module that comes with Python is a simple HTTP server that
provides standard GET and POST request handlers. You can easily set up a server on localhost to serve files. You can also write HTML files and create a working web application on localhost with the SimpleHTTPServer module.

Why Should You Use Python SimpleHTTPServer?

An advantage of the built-in HTTP server is that you don’t have to install and configure anything. The only thing that you need, is to have Python installed. That makes it perfect to use when you need a quick web server running and you don’t want to mess with setting up Apache or Ngnix-like servers.

SimpleHTTPServer is a simple and efficient tool to learn how a server or a web app works using GET requests and POST requests. You can use this to turn any directory in your system into your web server directory.

How do I Use Python SimpleHTTPServer?

To start an HTTP server on port 8000 (which is the default port), you can simply the following command in the command prompt.

python -m SimpleHTTPServer

The above command works for Python 2. To run SimpleHTTPServer in Python 3, you need to execute the following command.

python -m http.server

After execution of the above command, the python simpleHTTPserver will be started on your machine. You can observe this in the following example.

Python SimpleHTTPServer Running
Python SimpleHTTPServer Running

In the above image, you can observe that the server has started on the 8000 port.

To access the server using the web browser you can open the link localhost:8000 or 127.0.0.1:8000 on your web browser. There, you will find all the files of the directory in which the SimpleHTTPServer has been started. You can click on any file or directory to send a GET request to the server to access the files as shown below.

In the above video, you can observe that all the files in the directory in which the simpleHTTPserver is started are displayed in the browser. When we click on the httpserver_example folder, the browser issues a GET request. Then, the server displays the contents of the folder. Again, when we click on the files in the httpserver_example folder, the file contents are displayed on the screen. If a file cannot be displayed, it will be downloaded through your browser. Thus, the Python simpleHTTPServer module makes your file system into a temporary web server.

In the terminal where you started the server, you can observe the following outputs.

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [17/Jun/2023 10:46:52] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [17/Jun/2023 10:47:29] "GET /httpserver_example/ HTTP/1.1" 200 -
127.0.0.1 - - [17/Jun/2023 10:47:29] "GET /favicon.ico HTTP/1.1"
127.0.0.1 - - [17/Jun/2023 10:47:32] "GET /httpserver_example/pfb.html HTTP/1.1" 200 -
127.0.0.1 - - [17/Jun/2023 10:47:38] "GET /httpserver_example/pfb.txt HTTP/1.1" 200 -

In the terminal output, you can observe that the browser has issued a GET request every time we clicked on a folder or file name in the browser.

Instead of using the default 8000 port for running the simpleHTTPserver, you can specify the port number after the SimpleHTTPServer command as shown below.

$ python -m SimpleHTTPServer 8080

After execution of the above command, the Python SimpleHTTPServer will run on port 8080 instead of the port default port.

In Python 3, you can specify the port for running the Python simpleHTTPserver as shown below.

python -m http.server 8888

After executing the above command, the simple HTTP server will be started on the 8888 port instead of the 8000 port. You can observe this in the following image.

SimpleHTTPServer on Custom Port
SimpleHTTPServer on Custom Port

Suggested Reading: To read about how to write Python programs to serve files with custom paths using SimpleHTTPServer, you can read this article on SimpleHTTPServer with Default and Custom Paths.

How to Share Files and Directories Using SimpleHTTPserver?

To share files and directories using SimpleHTTPServer. you first need to move to the directory whose contents you want to share. For this, you can open a terminal and cd into whichever directory you wish to have accessible via browsers and HTTP. After that, you can start the server in the given directory.

cd /var/www/
$ python -m SimpleHTTPServer

After you hit enter, you should see the following message:

Serving HTTP on 0.0.0.0 port 8000 …

Then, you can open your favorite browser and put in any of the following addresses:

http://your_ip_address:8000
http://127.0.0.1:8000

If you don’t have an index.html file in the directory, then all files and directories will be listed as shown in the video example.

As long as the HTTP server is running, the terminal will update as data are loaded from the Python web server. You should see standard HTTP logging information (GET and PUSH), 404 errors, IP addresses, dates, times, and all that you would expect from a standard HTTP log as if you were tailing an Apache access log file.

SimpleHTTPServer is a great way of serving the contents of the current directory from the command line. While there are many web server software out there (Apache, Nginx), using Python
built-in HTTP server requires no installation and configuration.

Conclusion

In this article, we have discussed the basics of Python SimpleHTTPServer. To learn more about Python programming, you can read this article on string manipulation in Python. You might also like this article on list comprehension in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

The post How to use Python SimpleHTTPServer appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/modules-in-python/how-to-use-simplehttpserver/feed 1 5764
Python Secure FTP module https://www.pythonforbeginners.com/modules-in-python/python-secure-ftp-module Mon, 17 Jun 2013 13:57:14 +0000 https://www.pythonforbeginners.com/?p=5366 Overview In the previous post we covered the ftplib module in Python, which you can read more about here. In this post we will cover the pysftp module. SFTP (Secure File Transfer Protocol) is used for securely exchanging files over the Internet. What is it? pysftp is an easy to use sftp module that utilizes […]

The post Python Secure FTP module appeared first on PythonForBeginners.com.

]]>
Overview

In the previous post we covered the ftplib module in Python, which you can read
more about here. In this post we will cover the pysftp module.

SFTP (Secure File Transfer Protocol) is used for securely exchanging files
over the Internet.

What is it?

pysftp is an easy to use sftp module that utilizes paramiko and pycrypto.

It provides a simple interface to sftp.

Some of the features are:
Gracefully handles both RSA and DSS private key files automatically

Supports encrypted private key files.

Logging can now be enabled/disabled

Why should I use it?

When you want to securely exchange files over the Internet.

How do I install it?

pysftp is listed on PyPi and can be installed using pip.

# Search for pysftp
pip search pysftp

pysftp                    # - A friendly face on SFTP

#Install pysftp
pip install pysftp

How do I use it?

Using pysftp is easy and we will show some examples on how you can use it

List a remote directory

To connect to our FTP server, we first have to import the pysftp module and
specify (if applicable) server, username and password credentials.

After running this program, you should see all the files and directories of
the current directory of your FTP server.

import pysftp

srv = pysftp.Connection(host="your_FTP_server", username="your_username",
password="your_password")

# Get the directory and file listing
data = srv.listdir()

# Closes the connection
srv.close()

# Prints out the directories and files, line by line
for i in data:
    print i

Connection parameters

Arguments that are not given are guessed from the environment.

host

The Hostname of the remote machine.

username

Your username at the remote machine.(None)

private_key

Your private key file.(None)

password

Your password at the remote machine.(None)

port

The SSH port of the remote machine.(22)

private_key_pass

password to use if your private_key is encrypted(None)

log

log connection/handshake details (False)

Download / Upload a remote file

As in the previous example we first import the pysftp module and specify
(if applicable) server, username and password credentials.

We also import the sys module, since we want the user to specify the file to
download / upload.

import pysftp
import sys

# Defines the name of the file for download / upload
remote_file = sys.argv[1]

srv = pysftp.Connection(host="your_FTP_server", username="your_username",
password="your_password")

# Download the file from the remote server
srv.get(remote_file)

# To upload the file, simple replace get with put. 
srv.put(remote_file)

# Closes the connection
srv.close()

What’s the next step?

Play around with the script, change things and see what happens.

Try add error handling to it. What happens if no argument is passed?

Add some interaction to the program by prompting for input.

Sources

https://code.google.com/p/pysftp/
http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol

The post Python Secure FTP module appeared first on PythonForBeginners.com.

]]>
5366
Argparse Tutorial https://www.pythonforbeginners.com/argparse/argparse-tutorial Wed, 12 Jun 2013 00:35:06 +0000 https://www.pythonforbeginners.com/?p=5348 What is it? Parser for command-line options, arguments and subcommands Why use it? The argparse module makes it easy to write user-friendly command-line interfaces. How does it do that? The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help […]

The post Argparse Tutorial appeared first on PythonForBeginners.com.

]]>
What is it?

Parser for command-line options, arguments and subcommands

Why use it?

The argparse module makes it easy to write user-friendly command-line interfaces.

How does it do that?

The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Concept

When you run the “ls” command without any options, it will default displaying the contents of the current directory If you run “ls” on a different directory that you currently are in, you would type “ls directory_name”.

The “directory_name” is a “positional argument”, which means that the program know what to do with the value.

To get more information about a file we can use the “-l” switch.

The “-l” is knowns as an “optional argument” If you want to display the help text of the ls command, you would type “ls –help”

Argparse

To start using the argparse module, we first have to import it.

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

Run the code

Run the code with the –help option (Running the script without any options results in nothing displayed to stdout)

python program.py --help (or python program.py -h) 
usage: program.py [-h]

optional arguments:
  -h, --help  show this help message and exit

As seen above, even though we didnt specify any help arguments in our script, its still giving us a nice help message. This is the only option we get for free.

Positional arguments

In our “ls” example above, we made use of the positional arguments “ls directory_name”. Whenever we want to specify which command-line options the program will accept, we use the “add_argument()” method.

parser.add_argument("echo") 	# naming it "echo"
args = parser.parse_args()	# returns data from the options specified (echo)
print(args.echo)				

If we now run the code, we can see it requires us to specify an option

$ python program.py

usage: program.py [-h] echo
program.py: error: too few arguments

When we specify the echo option it will display “echo”

$ python program.py echo
echo

#Using the --help option
$ python program.py --help
usage: program.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit

Extending the help text

To get more help about our positional argument (echo), we have to change our script.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)

Result in this:

$ python program.py --help
usage: program.py [-h] echo

positional arguments:
  echo        echo the string you use here

optional arguments:
  -h, --help  show this help message and exit

Note: Argparse treats the options we give as a string, but we can change that.

Running the code with the type set to Integer

This code will treat the input as an integer.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print(args.square**2)

If we run the program with the –help option, we can see:

$ python program.py -h
usage: program.py [-h] square

positional arguments:
  square      display a square of a given number

optional arguments:
  -h, --help  show this help message and exit

Run the program

From the help text, we can see that if we give the program a number, it will give us the square back.

Cool, lets try it out:

$ python program.py 4
16

$ python program.py 10
100

If we would use a string instead of a number, the program will return an error

$ python program.py four

usage: program.py [-h] square

program.py: error: argument square: invalid int value: 'four'

Optional arguments

In our “ls” example above, we made use of the optional argument “-l” to get more information about a file. The program below will display something when –verbosity is specified and display nothing when not.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

An optional argument (or option) is (by default) given None as a value when its not being used. Using the –verbosity option, only two values are actually useful, True or False.

The keyword “action” is being given the value “store_true” which means that if the option is specifed, then assign the value “True” to args.verbose Not specifying the option implies False.

If we run the program with the –help option, we can see:

$ python program.py -h
usage: program.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity

Run the program using the –verbose option

$ python program.py --verbose
verbosity turned on

Short options

Using short versions of the options is as easy as:

parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")

The help text will updated with the short version.

Source

http://docs.python.org/dev/library/argparse.html

The post Argparse Tutorial appeared first on PythonForBeginners.com.

]]>
5348
How to use sh in Python https://www.pythonforbeginners.com/modules-in-python/how-to-use-sh-in-python Wed, 24 Apr 2013 13:09:25 +0000 https://www.pythonforbeginners.com/?p=5075 What is sh? sh is a unique subprocess wrapper that maps your system programs to Python functions dynamically. sh helps you write shell scripts in Python by giving you the good features of Bash (easy command calling, easy piping) with all the power and flexibility of Python. [source] Starting with sh sh is a full-fledged […]

The post How to use sh in Python appeared first on PythonForBeginners.com.

]]>
What is sh?

sh is a unique subprocess wrapper that maps your system programs to Python
functions dynamically. sh helps you write shell scripts in Python by giving you
the good features of Bash (easy command calling, easy piping) with all the power
and flexibility of Python. [source]

Starting with sh

sh is a full-fledged subprocess interface for Python that allows you to call any
program as if it were a function. sh lets you call just about anything that you
could run from a login shell much more neatly than you can with subprocess.Popen,
and more importantly lets you capture and parse the output much more readily.

Installation

The installation of sh is done through the pip command

pip install sh

Usage

The easiest way to get up and running is to import sh directly or import your
program from sh. Every command you want to run is imported like any other module.

That command is then usable just like a Python statement.

Arguments are passed per usual, and output can be captured and worked with in a
like fashion.

# get interface information
import sh
print sh.ifconfig("eth0")

from sh import ifconfig
print ifconfig("eth0")

# print the contents of this directory
print ls("-l")

# substitute the dash for an underscore for commands that have dashes in their names
sh.google_chrome("http://google.com”)

Executing Commands with sh

Commands are called just like functions.

“Note that these aren’t Python functions, these are running the binary commands
on your system dynamically by resolving your PATH, much like Bash does. In this
way, all the programs on your system are easily available in Python.”

Many programs have their own command subsets, like git (branch, checkout).

sh handles subcommands through attribute access.

from sh import git

# resolves to "git branch -v"
print(git.branch("-v"))

print(git("branch", "-v")) # the same command

Keyword Arguments

Keyword arguments also work like you’d expect: they get replaced with the
long-form and short-form commandline option. [source]

# Resolves to "curl http://duckduckgo.com/ -o page.html --silent"
sh.curl("http://duckduckgo.com/", o="page.html", silent=True)

# If you prefer not to use keyword arguments, this does the same thing
sh.curl("http://duckduckgo.com/", "-o", "page.html", "--silent")

# Resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home"
sh.adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True)

# or
sh.adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home”)

Finding Commands

“Which” finds the full path of a program, or returns None if it doesn’t exist.

This command is one of the few commands implemented as a Python function, and
therefore doesn’t rely on the “which” program actually existing.

print sh.which("python")     # "/usr/bin/python"
print sh.which("ls")         # "/bin/ls"

if not sh.which("supervisorctl"): sh.apt_get("install", "supervisor", “-y”)

There are many more features that you can use with sh, and you can find them all
in the official documentation.

Baking

sh is capable of “baking” arguments into commands.

# The idea here is that now every call to ls will have the “-la” arguments already specified.
from sh import ls

ls = ls.bake("-la")
print(ls) # "/usr/bin/ls -la"

# resolves to "ls -la /"
print(ls(“/“))
Baked ssh command

Calling “bake” on a command creates a callable object that automatically passes
along all of the arguments passed into “bake”.

# Without baking, calling uptime on a server would be a lot to type out:
serverX = ssh("myserver.com", "-p 1393", "whoami")

# To bake the common parameters into the ssh command
myserver = sh.ssh.bake("myserver.com", p=1393)

print(myserver) # "/usr/bin/ssh myserver.com -p 1393”

Now that the “myserver” callable represents a baked ssh command, you can call
anything on the server easily:

# resolves to "/usr/bin/ssh myserver.com -p 1393 tail /var/log/dumb_daemon.log -n 100"
print(myserver.tail("/var/log/dumb_daemon.log", n=100))

# check the uptime
print myserver.uptime()
 15:09:03 up 61 days, 22:56,  0 users,  load average: 0.12, 0.13, 0.05

For more advanced features, please see the official documentation.

Sources

https://github.com/amoffat/sh
https://github.com/Byzantium/Byzantium

The post How to use sh in Python appeared first on PythonForBeginners.com.

]]>
5075
Python and MySQL with MySQLdb https://www.pythonforbeginners.com/modules-in-python/python-and-mysql-with-mysqldb Mon, 03 Dec 2012 13:30:30 +0000 https://www.pythonforbeginners.com/?p=1845 Last week I was looking for a Python module that I could use to interact with a MySQL database server. MySQLdb is doing just that. “MySQLdb is a thin Python wrapper around _mysql which makes it compatible with the Python DB API interface (version 2). In reality, a fair amount of the code which implements […]

The post Python and MySQL with MySQLdb appeared first on PythonForBeginners.com.

]]>
Last week I was looking for a Python module that I could use to interact with a MySQL database server. MySQLdb is doing just that.

“MySQLdb is a thin Python wrapper around _mysql which makes it compatible with the Python DB API interface (version 2). In reality, a fair amount of the code which implements the API is in _mysql for the sake of efficiency.”

To install and use it, simply run: sudo apt-get install python-mysqldb

When that is done, you can start importing the MySQLdb module in your scripts.

I found this code snippet on Alex Harvey website

# Make the connection
connection = MySQLdb.connect(host='localhost',user='alex',passwd='secret',db='myDB')
cursor = connection.cursor()

# Lists the tables in demo
sql = "SHOW TABLES;"

# Execute the SQL query and get the response
cursor.execute(sql)
response = cursor.fetchall()

# Loop through the response and print table names
for row in response:
    print row[0]

For more examples on how to use MySQLdb in Python, please take a look on Zetcode.com.

The post Python and MySQL with MySQLdb appeared first on PythonForBeginners.com.

]]>
1845
Python Range Function https://www.pythonforbeginners.com/modules-in-python/python-range-function Mon, 15 Oct 2012 03:55:17 +0000 https://www.pythonforbeginners.com/?p=1376 The Range function The built-in range function in Python is very useful to generate sequences of numbers in the form of a list. The given end point is never part of the generated list; range(10) generates a list of 10 values, the legal indices for items of a sequence of length 10. It is possible […]

The post Python Range Function appeared first on PythonForBeginners.com.

]]>
The Range function

The built-in range function in Python is very useful to generate sequences of
numbers in the form of a list.

The given end point is never part of the generated list;

range(10) generates a list of 10 values, the legal indices for items of a
sequence of length 10.

It is possible to let the range start at another number, or to specify a
different increment (even negative;

Sometimes this is called the ‘step’):

Range Examples

>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

# You can use range() wherever you would use a list. 

a = range(1, 10) 
for i in a: 
    print i 

for a in range(21,-1,-2):
   print a,

#output>> 21 19 17 15 13 11 9 7 5 3 1


# We can use any size of step (here 2)
>>> range(0,20,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]

# The sequence will start at 0 by default. 
#If we only give one number for a range this replaces the end of range value.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# If we give floats these will first be reduced to integers. 
>>> range(-3.5,9.8)
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
More Reading

http://www.python.org

The post Python Range Function appeared first on PythonForBeginners.com.

]]>
1376
Python Standard Library vs Python Package Index https://www.pythonforbeginners.com/modules-in-python/standard-library-vs-package-index Thu, 20 Sep 2012 06:44:13 +0000 https://www.pythonforbeginners.com/?p=418 Python Modules In this post, we’ll look at the Python Standard Library and Python Package Index Python Standard Library URL:http://docs.python.org/library/index.html What it is: Collection of of modules that are already on the system, thus there is no need to install them. Just import the modules you want to use. Search for a module:http://docs.python.org/py-modindex.html Python Package […]

The post Python Standard Library vs Python Package Index appeared first on PythonForBeginners.com.

]]>
Python Modules

In this post, we’ll look at the Python Standard Library and Python Package Index

Python Standard Library

URL:http://docs.python.org/library/index.html

What it is:

Collection of of modules that are already on the system, thus there is no need to install them. Just import the modules you want to use. Search for a module:http://docs.python.org/py-modindex.html

Python Package Index

URL: http://pypi.python.org/pypi

What it is:

It’s a repository of software containing more than 2400 packages created by community members.

The post Python Standard Library vs Python Package Index appeared first on PythonForBeginners.com.

]]>
418
Python Modules https://www.pythonforbeginners.com/modules-in-python/python-modules Tue, 18 Sep 2012 14:47:13 +0000 https://www.pythonforbeginners.com/?p=101 This is a new series of articles here at Python for beginners, that are supposed to be a starting point for completely beginners of Python. See it as a cheat sheet, reference, manual or whatever you want. The purpose is to very short write down the basics of Python. This page will describe how to […]

The post Python Modules appeared first on PythonForBeginners.com.

]]>
This is a new series of articles here at Python for beginners, that are supposed to be a starting point for completely beginners of Python. See it as a cheat sheet, reference, manual or whatever you want. The purpose is to very short write down the basics of Python. This page will describe how to use Modules in Python.

Python Modules

Python modules makes the programming a lot easier. It’s basically a file that consist of already written code. When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is. There are different ways to import a module. This is also why Python comes with battery included

Importing Modules

Let’s how the different ways to import a module

import sys    		
#access module, after this you can use sys.name to refer to things defined in module sys.

from sys import stdout  
# access module without qualiying name. 
This reads from the module "sys" import "stdout", so that we would be able to 
refer "stdout"in our program.

from sys import *       
# access all functions/classes in the sys module. 

Catching Errors

I like to use the import statement to ensure that all modules can be loaded on the system. The Import Error basically means that you cannot use this module, and that you should look at the traceback to find out why.

Import sys
try:
    import BeautifulSoup
except ImportError:
    print 'Import not installed'
    sys.exit()

Python Standard Library

URL: http://docs.python.org/library/index.html Collection of of modules that are already on the system, there is no need to install them. Just import the modules you want to use. Search for a module: http://docs.python.org/py-modindex.html

Python Package Index

URL: http://pypi.python.org/pypi Created by community members. It’s a repository of software containing more than 2400 packages

The post Python Modules appeared first on PythonForBeginners.com.

]]>
101