python: Translate C examples into Python and include documentation.
[libguestfs.git] / python / examples / create_disk.py
1 # Example showing how to create a disk image.
2
3 import os
4 import guestfs
5
6 output = "disk.img"
7
8 g = guestfs.GuestFS ()
9
10 # Create a raw-format sparse disk image, 512 MB in size.
11 f = open (output, "w")
12 f.truncate (512 * 1024 * 1024)
13 f.close ()
14
15 # Set the trace flag so that we can see each libguestfs call.
16 g.set_trace (1)
17
18 # Set the autosync flag so that the disk will be synchronized
19 # automatically when the libguestfs handle is closed.
20 g.set_autosync (1)
21
22 # Attach the disk image to libguestfs.
23 g.add_drive_opts (output, format = "raw", readonly = 0)
24
25 # Run the libguestfs back-end.
26 g.launch ()
27
28 # Get the list of devices.  Because we only added one drive
29 # above, we expect that this list should contain a single
30 # element.
31 devices = g.list_devices ()
32 assert (len (devices) == 1)
33
34 # Partition the disk as one single MBR partition.
35 g.part_disk (devices[0], "mbr")
36
37 # Get the list of partitions.  We expect a single element, which
38 # is the partition we have just created.
39 partitions = g.list_partitions ()
40 assert (len (partitions) == 1)
41
42 # Create a filesystem on the partition.
43 g.mkfs ("ext4", partitions[0])
44
45 # Now mount the filesystem so that we can add files.
46 g.mount_options ("", partitions[0], "/")
47
48 # Create some files and directories.
49 g.touch ("/empty")
50 message = "Hello, world\n"
51 g.write ("/hello", message)
52 g.mkdir ("/foo")
53
54 # This one uploads the local file /etc/resolv.conf into
55 # the disk image.
56 g.upload ("/etc/resolv.conf", "/foo/resolv.conf")
57
58 # Because 'autosync' was set (above) we can just close the handle
59 # and the disk contents will be synchronized.  You can also do
60 # this manually by calling g.umount_all and g.sync.
61 del g