Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / Python
Tip/Trick

Creating Linux Swap Files Using Python

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Oct 2014GPL34 min read 18.1K   44   1   2
This tip describes how to create and delete Linux swap files using a Python script

Introduction

I would normally prefer not to create swap partitions while installing Linux on my own computers because the amount of memory they have is completely sufficient for my day to day work. But sometimes, it is useful to have a temporary swap space (for example when running a virtual machine that consumes lots of memory). In these situations, the solution is to create a swap file. Creating a swap file needs a couple of steps to be taken. Here is a Python script that does the steps on your behalf.

Background

To create a swap file, four steps must be taken. We will briefly discuss them.

1. Creating an Empty File

We have to begin by creating an empty file with the desired size. This can be done using “dd” command.

#dd if=/dev/zero of=myswapfile bs=1M count=blockcount

The command creates a file (named myswapfile) with the size of blockcount megabyes.(The “bs” option defines the block size and it is one magabyte in our exmaple).

The “if” option specifies the source file stream. We use the Linux built-in “zero” file which provides as many null characters as are read from it.

2. Setting Permissions

Although not necessary, it is a good idea to deny users other than root and the owner from interacting with the created file. The next command does this:

#chmod 600 myswapfile

3. Setting Up a Swap Area

Using the next command prepares the file for us:

#mkswap myswapfile

4. Enabling the New Swap Space

This is the only step that root permission is required so we need to use “sudo” command.

#sudo swapon myswapfile

Now our swap file is working. To prove this, use the following command:

#swapon -s

To disable the swap space, we have to take two steps:

1. Disabling the Swap Space

Again , root permission is required here.

#sudo swapoff myswapfile

2. Removing the File

To clean up completely, we remove the file from the file system.

#rm myswalfile

Using the Code

createswap.py is a python3 script. To use it, you can either give executable permission to it and use the following systax:

#./createswap.py

or use the Python engine explicitly:

#python3 createswap.py

To create a swap file, you need to define two values: file name and size.

#./createswap.py -f myswapfile -s 200

Note that the size is in megabytes. As discussed above, enabling a swap space requires root permission. The script asks for the permission automatically so you may be asked to enter the root password (There is no need to use “sudo ./createswap.py -f myswapfile -s 200” command).

The result is shown here:

Image 1

To switch the swap space off, use the following command:

#./createswap.py -o myswapfile

And here is the output:

Image 2

The script also accepts “–verbose” option which is helpful when something goes wrong. For example, suppose you wanted to turn a non-existence swap file off, you would type:

#./createswap.py -o badswapfile

and the output is:

Image 3

But the normal output does not tell you what happened exactly. Now try “--verbose” option:

#./createswap.py -o badswapfile –verbose

and now the output is more informative:

Image 4

Verbose output is also available when creating a new swap file.

Examining the Code

The code is made up of a couple of functions. The first one is “parse_args()” which uses “argparse” module to handle script arguments.

Two main functions are “create_swap()” and “drop_swap()” which create and drop swap files respectively.

The script grants root permission by using “sudo()” function which in turn executes “sudo id” command.

exec_step” method actually executes different needed Linux commands using “os.system()” function. All commands are executed by “sudo” command (It is necessary only for “swapon” command but to simplify the code, I used the same pattern for all commands).

command = 'sudo ' + command

In the normal mode, we do not need the output of executed commands so we use Linux stream redirection mechanism to redirect standard output streams and standard error streams to “/dev/null” built-in device. But in the verbose mode, this trick is not used.

if not is_verbose(): command += ' > /dev/null 2>&1'

Conclusion

Creating and removing swap files is not a difficult task that cannot be done by hand but having a script to quickly perform them comes in handy. It can save you time .

There is one more thing you should pay attention to. All swap areas that this script creates are not permanent. As soon as the system shuts down, they become detached from the Linux swap system. Files physically exist but you have to use “swapon” command to reattach them. To make a swap file permanent, the following line must be added to “/etc/fstab” file:

/myswapfile swap swap defaults 0 0

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Software Developer (Senior) Rayan Hamafza
Iran (Islamic Republic of) Iran (Islamic Republic of)
.Net Architect and Software Developer (Senior)

Comments and Discussions

 
GeneralIt remembers me of the Knoppix distro Pin
JH6429-Oct-14 12:43
JH6429-Oct-14 12:43 
GeneralRe: It remembers me of the Knoppix distro Pin
Farzan Hajian11-Nov-14 7:56
Farzan Hajian11-Nov-14 7:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.