[elbe-devel] [PATCH 03/10] add python3 support

Manuel Traut manut at linutronix.de
Fri Sep 29 00:11:39 CEST 2017


a complete python3 convert is not posible at the moment, because
python3-spyne is not available in debian.

this change enables building python3-elbe-* packages, so a
lot of elbe features can be used from python3 code.

urllib2 is no longar available in debian for python3, so
we use urllib3 if available

Signed-off-by: Manuel Traut <manut at linutronix.de>
---
 .gitignore                                         |  12 +-
 debian/compat                                      |   2 +-
 debian/control                                     | 123 +++++++++--
 debian/elbe-common.lintian-overrides               |   2 -
 debian/elbe-schema.install                         |   1 +
 ...-common.xmlcatalogs => elbe-schema.xmlcatalogs} |   0
 debian/python-elbe-bin.install                     |   2 +
 ...ildenv.install => python-elbe-buildenv.install} |   0
 ...e-common.install => python-elbe-common.install} |   3 -
 ...control.install => python-elbe-control.install} |   0
 debian/python3-elbe-buildenv.install               |  30 +++
 debian/python3-elbe-common.install                 |  32 +++
 debian/python3-elbe-control.install                |   5 +
 debian/rules                                       |   2 +-
 docs/Makefile                                      |   2 +-
 docs/conf.py                                       |  14 +-
 elbe                                               |  24 ++-
 elbepack/aptpkgutils.py                            |   2 +
 elbepack/aptprogress.py                            |  14 +-
 elbepack/asciidoclog.py                            |   4 +-
 elbepack/asyncworker.py                            |   9 +-
 elbepack/cdroms.py                                 |  14 +-
 elbepack/commands/add.py                           |  12 +-
 elbepack/commands/adjustpkgs.py                    |  12 +-
 elbepack/commands/bootup-check.py                  |  16 +-
 elbepack/commands/buildchroot.py                   |  18 +-
 elbepack/commands/buildsysroot.py                  |   7 +-
 elbepack/commands/check_updates.py                 |  22 +-
 elbepack/commands/chg_archive.py                   |  12 +-
 elbepack/commands/chroot.py                        |   7 +-
 elbepack/commands/control.py                       |  50 ++---
 elbepack/commands/daemon.py                        |  12 +-
 elbepack/commands/db.py                            |   7 +-
 elbepack/commands/debianize.py                     |  12 +-
 elbepack/commands/diff.py                          |  30 +--
 elbepack/commands/gen_update.py                    |  22 +-
 elbepack/commands/genlicence.py                    |   3 +-
 elbepack/commands/get_archive.py                   |  15 +-
 elbepack/commands/hdimg.py                         |  16 +-
 elbepack/commands/init.py                          |  36 ++--
 elbepack/commands/initvm.py                        |   8 +-
 elbepack/commands/mkcdrom.py                       |  16 +-
 elbepack/commands/parselicence.py                  |  63 +++---
 elbepack/commands/pbuilder.py                      |   8 +-
 elbepack/commands/pin_versions.py                  |  16 +-
 elbepack/commands/pkgdiff.py                       |  22 +-
 elbepack/commands/prjrepo.py                       |  55 ++---
 elbepack/commands/remove_sign.py                   |  10 +-
 elbepack/commands/setsel.py                        |  11 +-
 elbepack/commands/show.py                          |  42 ++--
 elbepack/commands/sign.py                          |   6 +-
 elbepack/commands/toolchainextract.py              |   2 +
 elbepack/commands/updated.py                       |   4 +-
 elbepack/commands/validate.py                      |  10 +-
 elbepack/commands/xsdtoasciidoc.py                 |   6 +-
 elbepack/config.py                                 |   5 +-
 elbepack/daemons/soap/__init__.py                  |  29 ++-
 elbepack/daemons/soap/authentication.py            |  26 +--
 elbepack/daemons/soap/datatypes.py                 |   1 +
 elbepack/daemons/soap/esoap.py                     |  29 ++-
 elbepack/daemons/soap/faults.py                    |  27 ++-
 elbepack/db.py                                     |  19 +-
 elbepack/dbaction.py                               |  56 ++---
 elbepack/debianize/barebox.py                      |   2 -
 elbepack/debianize/base.py                         |   4 +-
 elbepack/debianize/debianize.py                    |   2 -
 elbepack/debianize/kernel.py                       |   2 -
 elbepack/debianize/uboot.py                        |   4 +-
 elbepack/debianreleases.py                         |   4 +-
 elbepack/debpkg.py                                 |   4 +-
 elbepack/directories.py                            |   2 +
 elbepack/dosunix.py                                |  26 ++-
 elbepack/dump.py                                   |  18 +-
 elbepack/efilesystem.py                            |  17 +-
 elbepack/elbeproject.py                            |   4 +-
 elbepack/elbexml.py                                |  30 ++-
 elbepack/filesystem.py                             |   7 +-
 elbepack/finetuning.py                             |   8 +-
 elbepack/fstab.py                                  |   6 +-
 elbepack/gpg.py                                    |  42 ++--
 elbepack/hdimg.py                                  |  14 +-
 elbepack/initvmaction.py                           | 226 ++++++++++-----------
 elbepack/kvm.py                                    |   6 +-
 elbepack/licencexml.py                             |   6 +-
 elbepack/pbuilder.py                               |  31 ++-
 elbepack/pbuilderaction.py                         | 154 +++++++-------
 elbepack/persistency.py                            |  12 +-
 elbepack/pkgarchive.py                             |   4 +-
 elbepack/pkgutils.py                               |  35 ++--
 elbepack/projectmanager.py                         |   3 +-
 elbepack/repomanager.py                            |   2 +
 elbepack/rfs.py                                    |  28 ++-
 elbepack/rpcaptcache.py                            |   2 +
 elbepack/shellhelper.py                            |   2 +
 elbepack/soapclient.py                             | 112 +++++-----
 elbepack/templates.py                              |   8 +-
 elbepack/toolchain.py                              |   2 +
 elbepack/treeutils.py                              |  12 +-
 elbepack/updated.py                                |  20 +-
 elbepack/updated_monitors.py                       |   4 +-
 elbepack/updatepkg.py                              |  20 +-
 elbepack/validate.py                               |   2 +
 elbepack/version.py                                |   4 +-
 elbepack/virtapt.py                                |  14 +-
 elbepack/xmldefaults.py                            |  33 ++-
 elbepack/xmlpreprocess.py                          |   2 +
 elbepack/xsdtoasciidoc.mako                        |   2 +-
 elbepack/ziparchives.py                            |   3 +-
 setup.py                                           |   4 +-
 test/modify_rfs.py                                 |   8 +-
 test/updated.py                                    |  18 +-
 111 files changed, 1209 insertions(+), 843 deletions(-)
 delete mode 100644 debian/elbe-common.lintian-overrides
 create mode 100644 debian/elbe-schema.install
 rename debian/{elbe-common.xmlcatalogs => elbe-schema.xmlcatalogs} (100%)
 create mode 100644 debian/python-elbe-bin.install
 rename debian/{elbe-buildenv.install => python-elbe-buildenv.install} (100%)
 rename debian/{elbe-common.install => python-elbe-common.install} (95%)
 rename debian/{elbe-control.install => python-elbe-control.install} (100%)
 create mode 100644 debian/python3-elbe-buildenv.install
 create mode 100644 debian/python3-elbe-common.install
 create mode 100644 debian/python3-elbe-control.install

diff --git a/.gitignore b/.gitignore
index 461dc605..135c7d14 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,18 @@
 tags
+.pybuild
 elbe.egg-info
 debian/elbe-bootup-check/
-debian/elbe-buildenv/
-debian/elbe-common/
-debian/elbe-control/
+debian/python-elbe-buildenv/
+debian/python3-elbe-buildenv/
+debian/python-elbe-bin/
+debian/python-elbe-common/
+debian/python3-elbe-common/
+debian/python-elbe-control/
+debian/python3-elbe-control/
 debian/elbe-daemon/
 debian/elbe-debianize/
 debian/elbe-doc/
+debian/elbe-schema/
 debian/elbe-soap/
 debian/elbe-updated/
 *.debhelper
diff --git a/debian/compat b/debian/compat
index 7f8f011e..ec635144 100644
--- a/debian/compat
+++ b/debian/compat
@@ -1 +1 @@
-7
+9
diff --git a/debian/control b/debian/control
index fa12f1d6..a8c7ef2d 100644
--- a/debian/control
+++ b/debian/control
@@ -2,12 +2,16 @@ Source: elbe
 Section: misc
 Priority: optional
 Maintainer: Manuel Traut <manut at linutronix.de>
-Build-Depends: dh-python,
-  debhelper (>= 7),
-  dh-systemd (>= 1.5),
+Build-Depends: debhelper (>= 9),
+  dh-python,
+  dh-systemd,
+  python-setuptools,
   python (>= 2.7~),
   python-mako,
   python-lxml,
+  python3,
+  python3-mako,
+  python3-lxml,
   dia,
   asciidoc,
   xmlto,
@@ -27,9 +31,27 @@ Description: man-pages, examples and documentation
  man-pages for elbe and all elbe subcommands. Some documentation and howtos.
  And examples for several targets.
 
-Package: elbe-common
+Package: elbe-schema
 Architecture: all
+Conflicts: elbe-common
+Depends: ${misc:Depends}
+Description: xml schema files
+ Common files for ELBE (embedded linux build environment). These
+ schemas are used by ELBE.
+
+Package: python-elbe-bin
+Conflicts: elbe-common
+Architecture: all
+Depends: python-elbe-common (= ${binary:Version})
+Description: elbe executable
+ Common files for ELBE (embedded linux build environment). These
+ python-modules are shared by several elbe subcommands.
+
+Package: python-elbe-common
+Architecture: all
+Conflicts: elbe-common
 Depends: ${misc:Depends},
+  elbe-schema (= ${binary:Version}),
   python (>= 2.7~),
   python-lxml,
   python-apt,
@@ -42,6 +64,22 @@ Description: common files
  Common files for ELBE (embedded linux build environment). These
  python-modules are shared by several elbe subcommands.
 
+Package: python3-elbe-common
+Architecture: all
+Depends: ${misc:Depends},
+  elbe-schema (= ${binary:Version}),
+  python3,
+  python3-lxml,
+  python3-apt,
+  python3-gpgme,
+  python3-gpg,
+  python3-libvirt,
+  wget,
+  cpio
+Description: common files
+ Common files for ELBE (embedded linux build environment). These
+ python-modules are shared by several elbe subcommands.
+
 Package: elbe-debianize
 Architecture: all
 Depends: ${misc:Depends},
@@ -49,7 +87,7 @@ Depends: ${misc:Depends},
   devscripts,
   libdistro-info-perl,
   libparse-debcontrol-perl,
-  elbe-common (= ${binary:Version}),
+  python-elbe-common (= ${binary:Version}),
   python-mako,
   python-npyscreen
 Description: Wizard for debian foler generation
@@ -59,8 +97,8 @@ Package: elbe
 Architecture: all
 Depends: ${misc:Depends},
   python (>= 2.7~),
-  elbe-common (= ${binary:Version}),
-  elbe-control (= ${binary:Version}),
+  python-elbe-bin (= ${binary:Version}),
+  python-elbe-control (= ${binary:Version}),
   qemu-utils,
   qemu-kvm (>= 1:2.1),
   python-mako,
@@ -76,14 +114,51 @@ Package: elbe-daemon
 Architecture: all
 Depends: ${misc:Depends},
   python (>= 2.7~),
-  elbe-common (= ${binary:Version}),
-  elbe-buildenv (= ${binary:Version}),
+  python-elbe-common (= ${binary:Version}),
+  python-elbe-buildenv (= ${binary:Version}),
   python-cherrypy3, python-beaker, openssh-server, lsb-base (>= 3.0-6)
 Description: wsgi daemon interface
  subcommand to start wsgi services.
 
-Package: elbe-buildenv
+Package: python3-elbe-buildenv
 Architecture: all
+Depends: ${misc:Depends},
+  python3,
+  apt-rdepends,
+  binfmt-support,
+  debootstrap,
+  dosfstools,
+  dpkg-dev,
+  python3-elbe-common (= ${binary:Version}),
+  genisoimage,
+  mtd-utils,
+  python3-apt,
+  python3-mako,
+  python3-parted,
+  python3-passlib,
+  python3-sqlalchemy,
+  python3-debian,
+  qemu-user-static,
+  reprepro,
+  rsync,
+  kpartx,
+  squashfs-tools,
+  sudo,
+  pbuilder,
+  git,
+  ca-certificates,
+  subversion,
+  haveged
+Description: Embedded Linux Build Environment Server Component
+ This package is typically installed in a virtual machine (that can be created
+ with the 'elbe initvm create' command from the 'elbe' package). Several
+ subcommands need to be executed with root privileges. It is not recommended to
+ install this package on a native system.
+
+
+Package: python-elbe-buildenv
+Architecture: all
+Conflicts: elbe-buildenv
 Depends: ${misc:Depends},
   python (>= 2.7~),
   apt-rdepends,
@@ -91,7 +166,7 @@ Depends: ${misc:Depends},
   debootstrap,
   dosfstools,
   dpkg-dev,
-  elbe-common (= ${binary:Version}),
+  python-elbe-common (= ${binary:Version}),
   genisoimage,
   mtd-utils,
   python-apt,
@@ -123,7 +198,7 @@ Package: elbe-bootup-check
 Architecture: all
 Depends: ${misc:Depends},
   python (>= 2.7~),
-  elbe-common (= ${binary:Version}),
+  python-elbe-common (= ${binary:Version}),
   python-apt, lsb-base (>= 3.0-6)
 Description: bootup checker
  This package is typically installed on a embedded system. The bootup checker
@@ -134,28 +209,42 @@ Architecture: all
 Depends: ${misc:Depends},
   python (>= 2.7~),
   python-spyne,
-  elbe-buildenv (= ${binary:Version}),
+  python-elbe-buildenv (= ${binary:Version}),
   elbe-daemon (= ${binary:Version})
 Description: SOAP Interface for elbe buildenv
  Enables remote control of the elbe buildenv via SOAP.
 
-Package: elbe-control
+Package: python-elbe-control
 Architecture: all
+Conflicts: elbe-control
 Depends: ${misc:Depends},
   python (>= 2.7~),
   python-suds,
   python-debian,
-  elbe-common (= ${binary:Version}),
+  python-elbe-common (= ${binary:Version}),
+  libvirt-clients,
+  libvirt-daemon-system
+Description: Commandline Tool to control an elbe buildenv
+ The SOAP Interface is used to control an elbe buildenv.
+
+Package: python3-elbe-control
+Architecture: all
+Depends: ${misc:Depends},
+  python3,
+  python3-suds,
+  python3-debian,
+  python3-elbe-common (= ${binary:Version}),
   libvirt-clients,
   libvirt-daemon-system
 Description: Commandline Tool to control an elbe buildenv
  The SOAP Interface is used to control an elbe buildenv.
 
+
 Package: elbe-updated
 Architecture: all
 Depends: ${misc:Depends},
   python (>= 2.7~),
-  elbe-common (= ${binary:Version}),
+  python-elbe-common (= ${binary:Version}),
   python-lxml (>= 2.3.2-1),
   python-tz (>= 2012c-1),
   python-pyinotify,
@@ -168,6 +257,6 @@ Suggests: python-pyudev,
 Description: update daemon for embedded systems
  This package is typically installed on a embedded system. The update daemon
  monitors a directory or USB mounts. If an ELBE update file (generated by
- 'elbe gen_update' command from the 'elbe-buildenv' package) is placed in this
+ 'elbe gen_update' command from the 'python-elbe-buildenv' package) is placed in this
  directory the update will be applied.
  Downgrades are possible by the integrated SOAP interface.
diff --git a/debian/elbe-common.lintian-overrides b/debian/elbe-common.lintian-overrides
deleted file mode 100644
index 8f16ce0f..00000000
--- a/debian/elbe-common.lintian-overrides
+++ /dev/null
@@ -1,2 +0,0 @@
-# documentation is provided in elbe-doc
-elbe-common: binary-without-manpage usr/bin/elbe
diff --git a/debian/elbe-schema.install b/debian/elbe-schema.install
new file mode 100644
index 00000000..7cb5f41f
--- /dev/null
+++ b/debian/elbe-schema.install
@@ -0,0 +1 @@
+schema/*xsd usr/share/xml/elbe-common/
diff --git a/debian/elbe-common.xmlcatalogs b/debian/elbe-schema.xmlcatalogs
similarity index 100%
rename from debian/elbe-common.xmlcatalogs
rename to debian/elbe-schema.xmlcatalogs
diff --git a/debian/python-elbe-bin.install b/debian/python-elbe-bin.install
new file mode 100644
index 00000000..0afb26cf
--- /dev/null
+++ b/debian/python-elbe-bin.install
@@ -0,0 +1,2 @@
+./usr/bin/*
+./usr/share/man/man1/elbe.1
diff --git a/debian/elbe-buildenv.install b/debian/python-elbe-buildenv.install
similarity index 100%
rename from debian/elbe-buildenv.install
rename to debian/python-elbe-buildenv.install
diff --git a/debian/elbe-common.install b/debian/python-elbe-common.install
similarity index 95%
rename from debian/elbe-common.install
rename to debian/python-elbe-common.install
index 6c137e06..00757619 100644
--- a/debian/elbe-common.install
+++ b/debian/python-elbe-common.install
@@ -1,4 +1,3 @@
-./usr/bin/*
 ./usr/lib/python2.*/*-packages/elbepack/elbe-repo.pub
 ./usr/lib/python2.*/*-packages/elbepack/init/default-init.xml
 ./usr/lib/python2.*/*-packages/elbepack/init/Makefile.mako
@@ -31,5 +30,3 @@
 ./usr/lib/python2.*/*-packages/elbepack/version.py
 ./usr/lib/python2.*/*-packages/elbepack/virtapt.py
 ./usr/lib/python2.*/*-packages/elbepack/xmldefaults.py
-./usr/share/man/man1/elbe.1
-schema/*xsd	usr/share/xml/elbe-common/
diff --git a/debian/elbe-control.install b/debian/python-elbe-control.install
similarity index 100%
rename from debian/elbe-control.install
rename to debian/python-elbe-control.install
diff --git a/debian/python3-elbe-buildenv.install b/debian/python3-elbe-buildenv.install
new file mode 100644
index 00000000..1016df1e
--- /dev/null
+++ b/debian/python3-elbe-buildenv.install
@@ -0,0 +1,30 @@
+./usr/lib/python3.*/*-packages/elbepack/commands/adjustpkgs.py
+./usr/lib/python3.*/*-packages/elbepack/commands/buildchroot.py
+./usr/lib/python3.*/*-packages/elbepack/commands/buildsysroot.py
+./usr/lib/python3.*/*-packages/elbepack/commands/chroot.py
+./usr/lib/python3.*/*-packages/elbepack/commands/db.py
+./usr/lib/python3.*/*-packages/elbepack/commands/genlicence.py
+./usr/lib/python3.*/*-packages/elbepack/commands/gen_update.py
+./usr/lib/python3.*/*-packages/elbepack/commands/hdimg.py
+./usr/lib/python3.*/*-packages/elbepack/commands/mkcdrom.py
+./usr/lib/python3.*/*-packages/elbepack/commands/toolchainextract.py
+./usr/lib/python3.*/*-packages/elbepack/makofiles/preferences.mako
+./usr/lib/python3.*/*-packages/elbepack/hdimg.py
+./usr/lib/python3.*/*-packages/elbepack/db.py
+./usr/lib/python3.*/*-packages/elbepack/dbaction.py
+./usr/lib/python3.*/*-packages/elbepack/dump.py
+./usr/lib/python3.*/*-packages/elbepack/ziparchives.py
+./usr/lib/python3.*/*-packages/elbepack/repomanager.py
+./usr/lib/python3.*/*-packages/elbepack/finetuning.py
+./usr/lib/python3.*/*-packages/elbepack/rfs.py
+./usr/lib/python3.*/*-packages/elbepack/aptpkgutils.py
+./usr/lib/python3.*/*-packages/elbepack/asciidoclog.py
+./usr/lib/python3.*/*-packages/elbepack/cdroms.py
+./usr/lib/python3.*/*-packages/elbepack/debianreleases.py
+./usr/lib/python3.*/*-packages/elbepack/debpkg.py
+./usr/lib/python3.*/*-packages/elbepack/efilesystem.py
+./usr/lib/python3.*/*-packages/elbepack/fstab.py
+./usr/lib/python3.*/*-packages/elbepack/persistency.py
+./usr/lib/python3.*/*-packages/elbepack/rpcaptcache.py
+./usr/lib/python3.*/*-packages/elbepack/updatepkg.py
+./usr/lib/python3.*/*-packages/elbepack/pbuilder.py
diff --git a/debian/python3-elbe-common.install b/debian/python3-elbe-common.install
new file mode 100644
index 00000000..1c94cd3b
--- /dev/null
+++ b/debian/python3-elbe-common.install
@@ -0,0 +1,32 @@
+./usr/lib/python3.*/*-packages/elbepack/elbe-repo.pub
+./usr/lib/python3.*/*-packages/elbepack/init/default-init.xml
+./usr/lib/python3.*/*-packages/elbepack/init/Makefile.mako
+./usr/lib/python3.*/*-packages/elbepack/init/libvirt.xml.mako
+./usr/lib/python3.*/*-packages/elbepack/init/apt.conf.mako
+./usr/lib/python3.*/*-packages/elbepack/init/preseed.cfg.mako
+./usr/lib/python3.*/*-packages/elbepack/init/init-elbe.sh.mako
+./usr/lib/python3.*/*-packages/elbepack/__init__.py
+./usr/lib/python3.*/*-packages/elbepack/commands/__init__.py
+./usr/lib/python3.*/*-packages/elbepack/aptprogress.py
+./usr/lib/python3.*/*-packages/elbepack/config.py
+./usr/lib/python3.*/*-packages/elbepack/default-preseed.xml
+./usr/lib/python3.*/*-packages/elbepack/directories.py
+./usr/lib/python3.*/*-packages/elbepack/dosunix.py
+./usr/lib/python3.*/*-packages/elbepack/elbexml.py
+./usr/lib/python3.*/*-packages/elbepack/elbeproject.py
+./usr/lib/python3.*/*-packages/elbepack/filesystem.py
+./usr/lib/python3.*/*-packages/elbepack/gpg.py
+./usr/lib/python3.*/*-packages/elbepack/initvmaction.py
+./usr/lib/python3.*/*-packages/elbepack/kvm.py
+./usr/lib/python3.*/*-packages/elbepack/licencexml.py
+./usr/lib/python3.*/*-packages/elbepack/pbuilderaction.py
+./usr/lib/python3.*/*-packages/elbepack/pkgutils.py
+./usr/lib/python3.*/*-packages/elbepack/xmlpreprocess.py
+./usr/lib/python3.*/*-packages/elbepack/shellhelper.py
+./usr/lib/python3.*/*-packages/elbepack/templates.py
+./usr/lib/python3.*/*-packages/elbepack/toolchain.py
+./usr/lib/python3.*/*-packages/elbepack/treeutils.py
+./usr/lib/python3.*/*-packages/elbepack/validate.py
+./usr/lib/python3.*/*-packages/elbepack/version.py
+./usr/lib/python3.*/*-packages/elbepack/virtapt.py
+./usr/lib/python3.*/*-packages/elbepack/xmldefaults.py
diff --git a/debian/python3-elbe-control.install b/debian/python3-elbe-control.install
new file mode 100644
index 00000000..965f2d4f
--- /dev/null
+++ b/debian/python3-elbe-control.install
@@ -0,0 +1,5 @@
+./usr/lib/python3.*/*-packages/elbepack/commands/control.py
+./usr/lib/python3.*/*-packages/elbepack/commands/initvm.py
+./usr/lib/python3.*/*-packages/elbepack/commands/pbuilder.py
+./usr/lib/python3.*/*-packages/elbepack/commands/prjrepo.py
+./usr/lib/python3.*/*-packages/elbepack/soapclient.py
diff --git a/debian/rules b/debian/rules
index 39160f30..cf2bcb12 100755
--- a/debian/rules
+++ b/debian/rules
@@ -26,4 +26,4 @@ override_dh_install:
 	dh_installxmlcatalogs
 
 %:
-	dh --with systemd --buildsystem=python_distutils --with python2 $@
+	dh $@ --with systemd --buildsystem=pybuild --with python2,python3
diff --git a/docs/Makefile b/docs/Makefile
index ce5247d2..2db7fa02 100644
--- a/docs/Makefile
+++ b/docs/Makefile
@@ -143,7 +143,7 @@ elbeoverview-en-ie.html: elbeoverview-en.txt elbe-process.png emu-process.png
 	$(ASCIIDOC) -b html5 -a icons -a toc2 -a theme=flask -o elbeoverview-en.html elbeoverview-en.txt
 
 elbe-schema-reference.txt: ../schema/dbsfed.xsd ../elbepack/xsdtoasciidoc.mako
-	../elbe xsdtoasciidoc --output elbe-schema-reference.txt ../schema/dbsfed.xsd
+	python3 ../elbe xsdtoasciidoc --output elbe-schema-reference.txt ../schema/dbsfed.xsd
 	$(ASCIIDOC) -a toc2 $(ASCIIDOC_EXTRA) $(ASCIIDOC_DATA_URI) -b xhtml11 elbe-schema-reference.txt
 
 elbe-schema-reference.html: %.html : %.txt
diff --git a/docs/conf.py b/docs/conf.py
index d5ea6aad..1a20db65 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -47,9 +47,9 @@ source_suffix = '.rst'
 master_doc = 'index'
 
 # General information about the project.
-project = u'ELBE'
-copyright = u'2017, Linutronix GmbH'
-author = u'Torben Hohn, Manuel Traut'
+project = 'ELBE'
+copyright = '2017, Linutronix GmbH'
+author = 'Torben Hohn, Manuel Traut'
 
 # The version info for the project you're documenting, acts as replacement for
 # |version| and |release|, also used in various other places throughout the
@@ -128,8 +128,8 @@ latex_elements = {
 # (source start file, target name, title,
 #  author, documentclass [howto, manual, or own class]).
 latex_documents = [
-    (master_doc, 'ELBE.tex', u'ELBE Documentation',
-     u'Torben Hohn, Manuel Traut', 'manual'),
+    (master_doc, 'ELBE.tex', 'ELBE Documentation',
+     'Torben Hohn, Manuel Traut', 'manual'),
 ]
 
 
@@ -138,7 +138,7 @@ latex_documents = [
 # One entry per manual page. List of tuples
 # (source start file, name, description, authors, manual section).
 man_pages = [
-    (master_doc, 'elbe', u'ELBE Documentation',
+    (master_doc, 'elbe', 'ELBE Documentation',
      [author], 1)
 ]
 
@@ -149,7 +149,7 @@ man_pages = [
 # (source start file, target name, title, author,
 #  dir menu entry, description, category)
 texinfo_documents = [
-    (master_doc, 'ELBE', u'ELBE Documentation',
+    (master_doc, 'ELBE', 'ELBE Documentation',
      author, 'ELBE', 'One line description of project.',
      'Miscellaneous'),
 ]
diff --git a/elbe b/elbe
index 269b1920..2a9e5902 100755
--- a/elbe
+++ b/elbe
@@ -18,19 +18,21 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
+import os
 import sys
 
 import elbepack.commands
 from elbepack.version import elbe_version, running_os
 from elbepack.directories import init_directories, get_cmdlist
 
-
 def usage():
-    print 'elbe v' + elbe_version
-    print 'need a subcommand: e.g. \'elbe initvm\'. \n\
-    Available subcommands are: \n'
+    print("elbe v%s" % elbe_version)
+    print("need a subcommand: e.g. \'elbe initvm\'. \n\
+    Available subcommands are: \n")
     for i in get_cmdlist():
-        print '        * '+i
+        print("        * %s" % i)
 
 # First initialise the directories module
 # so that it knows, where the current elbe
@@ -43,13 +45,21 @@ if (len(sys.argv) < 2):
     sys.exit(20)
 
 if sys.argv[1] == "--version":
-    print 'elbe v' + elbe_version + ' ' + running_os[0] + ' ' + running_os[1]
+    print("elbe v %s %s %s" % (elbe_version, running_os[0], running_os[1]))
     sys.exit(0)
 
 cmd_list = get_cmdlist()
 
+if sys.argv[1] == "--test-commands":
+    for cmd in cmd_list:
+        os.system ("./elbe %s" % cmd)
+
+    print("all commands tested")
+    sys.exit(0)
+
+
 if not sys.argv[1] in cmd_list:
-    print "Unknown subcommand !\n"
+    print("Unknown subcommand !\n")
     usage()
     sys.exit(20)
 
diff --git a/elbepack/aptpkgutils.py b/elbepack/aptpkgutils.py
index e21f9b8d..0c3f264d 100644
--- a/elbepack/aptpkgutils.py
+++ b/elbepack/aptpkgutils.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 MARKED_INSTALL = 0
 MARKED_UPGRADE = 1
 MARKED_DELETE = 2
diff --git a/elbepack/aptprogress.py b/elbepack/aptprogress.py
index 009a11bc..5a86784f 100644
--- a/elbepack/aptprogress.py
+++ b/elbepack/aptprogress.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from apt.progress.base import InstallProgress, AcquireProgress, OpProgress
 from apt_pkg import size_to_str
 import os
@@ -36,7 +38,7 @@ class ElbeInstallProgress (InstallProgress):
         if self.cb:
             self.cb (line)
         else:
-            print line
+            print(line)
 
     def processing (self, pkg, stage):
         self.write ("processing: " + pkg + " - " + stage)
@@ -51,7 +53,7 @@ class ElbeInstallProgress (InstallProgress):
         try:
             obj.do_install (self.fileno)
         except AttributeError:
-            print 'installing .deb files is not supported by elbe progress'
+            print("installing .deb files is not supported by elbe progress")
             raise SystemError
         return 0
 
@@ -68,7 +70,7 @@ class ElbeAcquireProgress (AcquireProgress):
 
     def __init__ (self, cb=None):
         AcquireProgress.__init__ (self)
-        self._id = long(1)
+        self._id = int(1)
         self.cb = cb
 
     def write (self, line):
@@ -76,7 +78,7 @@ class ElbeAcquireProgress (AcquireProgress):
         if self.cb:
             self.cb (line)
         else:
-            print line
+            print(line)
 
     def ims_hit(self, item):
         line = 'Hit ' + item.description
@@ -106,7 +108,7 @@ class ElbeOpProgress (OpProgress):
 
     def __init__ (self, cb=None):
         OpProgress.__init__ (self)
-        self._id = long(1)
+        self._id = int(1)
         self.cb = cb
 
     def write (self, line):
@@ -114,7 +116,7 @@ class ElbeOpProgress (OpProgress):
         if self.cb:
             self.cb (line)
         else:
-            print line
+            print(line)
     def update (self, percent=None):
         pass
     def done (self):
diff --git a/elbepack/asciidoclog.py b/elbepack/asciidoclog.py
index fea37212..f96ed547 100644
--- a/elbepack/asciidoclog.py
+++ b/elbepack/asciidoclog.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 
diff --git a/elbepack/asyncworker.py b/elbepack/asyncworker.py
index ac9eb273..95e91ce4 100644
--- a/elbepack/asyncworker.py
+++ b/elbepack/asyncworker.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,11 +16,13 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from threading import Thread
-from Queue import Queue
+from queue import Queue
 from os import path, getcwd, chdir
 from contextlib import contextmanager
-from urllib import quote
+from urllib.parse import quote
 import traceback
 
 from elbepack.db import get_versioned_filename
@@ -32,7 +32,6 @@ from elbepack.pkgarchive import gen_binpkg_archive, checkout_binpkg_archive
 from elbepack.rfs import DebootstrapException
 from elbepack.elbeproject import AptCacheCommitError, AptCacheUpdateError
 
-
 class AsyncWorkerJob(object):
     def __init__ (self, project):
         self.project = project
diff --git a/elbepack/cdroms.py b/elbepack/cdroms.py
index 51c5cdf2..742150ae 100644
--- a/elbepack/cdroms.py
+++ b/elbepack/cdroms.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 
 from apt.package import FetchError
@@ -178,17 +180,17 @@ def mk_binary_cdrom(rfs, arch, codename, init_codename, xml, target, log, cdrom_
     # to make the installer accept this as a CDRom
     repo_fs = Filesystem( repo_path )
     repo_fs.mkdir_p (".disk")
-    repo_fs.write_file (".disk/base_installable", 0644, "main\n")
-    repo_fs.write_file (".disk/base_components", 0644, "main\n")
-    repo_fs.write_file (".disk/cd_type", 0644, "not_complete\n")
-    repo_fs.write_file (".disk/info", 0644, "elbe inst cdrom - full cd\n")
+    repo_fs.write_file (".disk/base_installable", 0o644, "main\n")
+    repo_fs.write_file (".disk/base_components", 0o644, "main\n")
+    repo_fs.write_file (".disk/cd_type", 0o644, "not_complete\n")
+    repo_fs.write_file (".disk/info", 0o644, "elbe inst cdrom - full cd\n")
     repo_fs.symlink (".", "debian", allow_exists=True)
-    repo_fs.write_file ("md5sum.txt", 0644, "")
+    repo_fs.write_file ("md5sum.txt", 0o644, "")
 
     # write source xml onto cdrom
     xml.xml.write (repo_fs.fname ('source.xml'))
 
     target_repo_fs = Filesystem( target_repo_path )
-    target_repo_fs.write_file (".aptignr", 0644, "")
+    target_repo_fs.write_file (".aptignr", 0o644, "")
 
     return repo.buildiso( os.path.join( target, "bin-cdrom.iso" ) )
diff --git a/elbepack/commands/add.py b/elbepack/commands/add.py
index 2b1e344c..ce774b9c 100644
--- a/elbepack/commands/add.py
+++ b/elbepack/commands/add.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 
 from elbepack.elbexml import ElbeXML
@@ -29,25 +29,25 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) < 2:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     try:
         xml = ElbeXML ( args[0] )
     except Exception as e:
-        print "Error reading xml file: %s" % str(e)
+        print(("Error reading xml file: %s" % str(e)))
         sys.exit(20)
 
     for a in args[1:]:
         try:
             xml.add_target_package( a )
         except Exception as e:
-            print "Error adding package %s: %s" % (a, str(e))
+            print(("Error adding package %s: %s" % (a, str(e))))
             sys.exit(20)
 
     try:
         xml.xml.write( args[0] )
     except:
-        print "Unable to write new xml file"
+        print("Unable to write new xml file")
         sys.exit(20)
diff --git a/elbepack/commands/adjustpkgs.py b/elbepack/commands/adjustpkgs.py
index 4c8d1779..9a0e369c 100644
--- a/elbepack/commands/adjustpkgs.py
+++ b/elbepack/commands/adjustpkgs.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from optparse import OptionParser
 
 from elbepack.asciidoclog import ASCIIDocLog
@@ -53,7 +53,7 @@ class adjpkg(object):
                     continue
                 if p.essential or p.is_auto_installed or (p.name in pkglist) or p.installed.priority == "important" or p.installed.priority == "required":
                     continue
-                print "MARK REMOVE %s" % p.name
+                print(("MARK REMOVE %s" % p.name))
                 p.mark_delete( auto_fix=False, purge=True )
 
             for name in pkglist:
@@ -66,7 +66,7 @@ class adjpkg(object):
                 cp = cache[name]
 
                 cp.mark_install()
-                print "MARK INSTALL %s" % cp.name
+                print(("MARK INSTALL %s" % cp.name))
 
             cache.commit(apt.progress.base.AcquireProgress(),
                          apt.progress.base.InstallProgress())
@@ -80,7 +80,7 @@ class adjpkg(object):
                     continue
                 if p.is_auto_removable:
                     p.mark_delete( purge=True )
-                    print "MARKED AS AUTOREMOVE %s" % p.name
+                    print(("MARKED AS AUTOREMOVE %s" % p.name))
 
         cache.commit(apt.progress.base.AcquireProgress(),
                      apt.progress.base.InstallProgress())
@@ -97,7 +97,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
diff --git a/elbepack/commands/bootup-check.py b/elbepack/commands/bootup-check.py
index c7e22c82..96358813 100755
--- a/elbepack/commands/bootup-check.py
+++ b/elbepack/commands/bootup-check.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import apt
 import apt_pkg
 
@@ -33,7 +33,7 @@ def is_installed (ip, cache):
     try:
         p = cache[ip.et.text]
     except KeyError:
-        print '%s is not in local apt' % ip.et.text
+        print(("%s is not in local apt" % ip.et.text))
         return False
     if p.current_state == apt_pkg.CURSTATE_INSTALLED:
         return True
@@ -50,26 +50,26 @@ def bootup_check (xml):
     for p in hl_cache:
         if p.is_installed:
             if not is_in_fpl (p, fpl):
-                print '%s installed by user' % p.name
+                print(("%s installed by user" % p.name))
 
     for ip in fpl:
          if not is_installed (ip, cache):
-                print '%s removed by user' % ip.et.text
+                print(("%s removed by user" % ip.et.text))
 
 def bootup_info ():
     with open ("/etc/elbe_version", 'r') as ev:
-        print ev.read()
+        print((ev.read()))
 
 def run_command (argv):
     try:
         xml = etree ("/etc/elbe_base.xml")
     except IOError:
-        print '/etc/elbe_base.xml removed by user'
+        print("/etc/elbe_base.xml removed by user")
         return -1
 
     bootup_check (xml)
     try:
         bootup_info ()
     except IOError:
-        print '/etc/elbe_version removed by user'
+        print("/etc/elbe_version removed by user")
         return -1
diff --git a/elbepack/commands/buildchroot.py b/elbepack/commands/buildchroot.py
index 56f69723..3725dd5a 100644
--- a/elbepack/commands/buildchroot.py
+++ b/elbepack/commands/buildchroot.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from optparse import OptionParser
 import sys
 
@@ -85,23 +85,23 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "wrong number of arguments"
+        print("wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     if not opt.target:
-        print "No target specified"
+        print("No target specified")
         sys.exit(20)
 
     if opt.skip_cdrom:
-        print "WARNING: Skip CDROMS is now the default, use --build-bin to build binary CDROM"
+        print("WARNING: Skip CDROMS is now the default, use --build-bin to build binary CDROM")
 
     try:
         project = ElbeProject( opt.target, args[0], opt.output, opt.name,
                 opt.buildtype, opt.skip_validation )
     except ValidationError as e:
-        print str(e)
-        print "xml validation failed. Bailing out"
+        print((str(e)))
+        print("xml validation failed. Bailing out")
         sys.exit(20)
 
     try:
@@ -109,12 +109,12 @@ def run_command( argv ):
                 opt.build_sources, opt.cdrom_size, opt.debug, opt.skip_pkglist,
                 opt.skip_pbuild )
     except CommandError as ce:
-        print "command in project build failed:", ce.cmd
+        print(("command in project build failed: %s" % ce.cmd))
         sys.exit(20)
 
     try:
         db = ElbeDB()
         db.save_project (project)
     except OperationalError:
-        print "failed to save project in database"
+        print("failed to save project in database")
         sys.exit(20)
diff --git a/elbepack/commands/buildsysroot.py b/elbepack/commands/buildsysroot.py
index 80f3782f..5cd62e52 100644
--- a/elbepack/commands/buildsysroot.py
+++ b/elbepack/commands/buildsysroot.py
@@ -16,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from optparse import OptionParser
 import sys
@@ -34,7 +35,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "wrong number of arguments"
+        print("wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
@@ -42,8 +43,8 @@ def run_command( argv ):
         project = ElbeProject( args[0], override_buildtype=opt.buildtype,
                 skip_validate=opt.skip_validation )
     except ValidationError as e:
-        print str(e)
-        print "xml validation failed. Bailing out"
+        print((str(e)))
+        print("xml validation failed. Bailing out")
         sys.exit(20)
 
     project.build_sysroot ()
diff --git a/elbepack/commands/check_updates.py b/elbepack/commands/check_updates.py
index c3e9930a..cc0669eb 100644
--- a/elbepack/commands/check_updates.py
+++ b/elbepack/commands/check_updates.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 
@@ -37,19 +39,19 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     if not opt.skip_validation:
         validation = validate_xml (args[0])
         if len (validation) != 0:
-            print "xml validation failed. Bailing out"
+            print("xml validation failed. Bailing out")
             for i in validation:
-                print i
+                print(i)
             sys.exit(20)
 
-    print "checking %s" % args[0]
+    print("checking %s" % args[0])
 
     xml = etree( args[0] )
 
@@ -93,10 +95,10 @@ def run_command( argv ):
 
         if not pname in v.cache:
             if pauto == 'false':
-                print pname, "does not exist in cache but is specified in pkg-list"
+                print("%s does not exist in cache but is specified in pkg-list" % pname)
                 errors += 1
             else:
-                print pname, "is no more required"
+                print("%s is no more required" % pname)
                 required_updates += 1
 
             continue
@@ -106,18 +108,18 @@ def run_command( argv ):
         if d.marked_install( centry ):
             cver = d.get_candidate_ver( v.cache[pname] ).ver_str
             if pver != cver:
-                print pname, "%s != %s" % (pver, cver)
+                print("%s: %s != %s" % (pname, pver, cver))
                 required_updates += 1
 
     sys.stdout.flush()
     sys.stderr.flush()
     if errors > 0:
-        print errors, "Errors occured, xml files needs fixing"
+        print("%d Errors occured, xml files needs fixing" % errors)
         if opt.script:
             os.system( "%s ERRORS %s" % (opt.script, args[0]) )
     elif required_updates > 0:
-        print required_updates, "updates required"
+        print("%d updates required" % required_updates)
         if opt.script:
             os.system( "%s UPDATE %s" % (opt.script, args[0]) )
     else:
-        print "No Updates available"
+        print("No Updates available")
diff --git a/elbepack/commands/chg_archive.py b/elbepack/commands/chg_archive.py
index 66c53d28..860dc1b1 100644
--- a/elbepack/commands/chg_archive.py
+++ b/elbepack/commands/chg_archive.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 import os
 
@@ -51,14 +51,14 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 2:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     try:
         xml = etree( args[0] )
     except:
-        print "Error reading xml file!"
+        print("Error reading xml file!")
         sys.exit(20)
 
     if os.path.isdir (args[1]):
@@ -76,13 +76,13 @@ def run_command( argv ):
         arch = xml.ensure_child( "archive" )
         arch.set_text( enbase( archive ) )
     except:
-        print "Error reading archive"
+        print("Error reading archive")
         sys.exit(20)
 
     try:
         xml.write( args[0] )
     except:
-        print "Unable to write new xml file"
+        print("Unable to write new xml file")
         sys.exit(20)
 
     if os.path.isdir (args[1]):
diff --git a/elbepack/commands/chroot.py b/elbepack/commands/chroot.py
index 29e8de38..70f90b55 100644
--- a/elbepack/commands/chroot.py
+++ b/elbepack/commands/chroot.py
@@ -16,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from optparse import OptionParser
 import sys
@@ -38,7 +39,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) < 1:
-        print "wrong number of arguments"
+        print("wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
@@ -46,8 +47,8 @@ def run_command( argv ):
         project = ElbeProject(args[0], override_buildtype=opt.buildtype,
                 skip_validate=opt.skip_validation, url_validation=ValidationMode.NO_CHECK)
     except ValidationError as e:
-        print str(e)
-        print "xml validation failed. Bailing out"
+        print((str(e)))
+        print("xml validation failed. Bailing out")
         sys.exit(20)
 
     os.environ["LANG"] = "C"
diff --git a/elbepack/commands/control.py b/elbepack/commands/control.py
index 8208df1d..83041beb 100755
--- a/elbepack/commands/control.py
+++ b/elbepack/commands/control.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -25,7 +23,13 @@ import sys
 
 from optparse import (OptionParser, OptionGroup)
 from suds import WebFault
-from urllib2 import URLError
+
+# different module names in python2 and 3
+try:
+    from urllib.error import URLError
+except ImportError:
+    from urllib2 import URLError
+
 from httplib import BadStatusLine
 
 from elbepack.soapclient import ClientAction, ElbeSoapClient
@@ -95,41 +99,41 @@ def run_command (argv):
     args = args[2:]
 
     if len(args) < 1:
-        print ('elbe control - no subcommand given', file=sys.stderr)
+        print("elbe control - no subcommand given", file=sys.stderr)
         ClientAction.print_actions ()
         return
 
     try:
         control = ElbeSoapClient (opt.host, opt.port, opt.user, opt.passwd, debug=opt.debug, retries=int(opt.retries))
     except socket.error as e:
-        print ("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr)
-        print ("", file=sys.stderr)
-        print ("Check, wether the Soap Server is running inside the initvm", file=sys.stderr)
-        print ("try 'elbe initvm attach'", file=sys.stderr)
+        print("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr)
+        print("", file=sys.stderr)
+        print("Check, wether the Soap Server is running inside the initvm", file=sys.stderr)
+        print("try 'elbe initvm attach'", file=sys.stderr)
         sys.exit(10)
     except URLError as e:
-        print ("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr)
-        print ("", file=sys.stderr)
-        print ("Check, wether the initvm is actually running.", file=sys.stderr)
-        print ("try 'elbe initvm start'", file=sys.stderr)
+        print("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr)
+        print("", file=sys.stderr)
+        print("Check, wether the initvm is actually running.", file=sys.stderr)
+        print("try 'elbe initvm start'", file=sys.stderr)
         sys.exit(10)
     except BadStatusLine as e:
-        print ("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr)
-        print ("", file=sys.stderr)
-        print ("Check, wether the initvm is actually running.", file=sys.stderr)
-        print ("try 'elbe initvm start'", file=sys.stderr)
+        print("Failed to connect to Soap server %s:%s\n" % (opt.host, opt.port), file=sys.stderr)
+        print("", file=sys.stderr)
+        print("Check, wether the initvm is actually running.", file=sys.stderr)
+        print("try 'elbe initvm start'", file=sys.stderr)
         sys.exit(10)
 
     try:
         v_server = control.service.get_version ()
         if v_server != elbe_version:
-            print ("elbe v%s is used in initvm, this is not compatible with \
+            print("elbe v%s is used in initvm, this is not compatible with \
 elbe v%s that is used on this machine. Please install same \
 versions of elbe in initvm and on your machine." % (v_server, elbe_version), file=sys.stderr)
             if not (opt.ignore_version):
                 sys.exit (20)
     except AttributeError:
-        print ("the elbe installation inside the initvm doesn't provide a \
+        print("the elbe installation inside the initvm doesn't provide a \
 get_version interface. Please create a new initvm or upgrade \
 elbe inside the existing initvm.", file=sys.stderr)
         if not (opt.ignore_version):
@@ -138,7 +142,7 @@ elbe inside the existing initvm.", file=sys.stderr)
     try:
         action = ClientAction (args[0])
     except KeyError:
-        print ('elbe control - unknown subcommand', file=sys.stderr)
+        print("elbe control - unknown subcommand", file=sys.stderr)
         ClientAction.print_actions ()
         sys.exit(20)
 
@@ -147,10 +151,10 @@ elbe inside the existing initvm.", file=sys.stderr)
     try:
         action.execute (control, opt, args[1:])
     except WebFault as e:
-        print ('Server returned error:', file=sys.stderr)
-        print ('', file=sys.stderr)
+        print("Server returned error:", file=sys.stderr)
+        print("", file=sys.stderr)
         if hasattr (e.fault, 'faultstring'):
-            print (e.fault.faultstring, file=sys.stderr)
+            print(e.fault.faultstring, file=sys.stderr)
         else:
-            print (e, file=sys.stderr)
+            print(e, file=sys.stderr)
         sys.exit(5)
diff --git a/elbepack/commands/daemon.py b/elbepack/commands/daemon.py
index b670d06d..ca137675 100644
--- a/elbepack/commands/daemon.py
+++ b/elbepack/commands/daemon.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import cherrypy
 
 from optparse import OptionParser
@@ -32,7 +34,7 @@ def run_command( argv ):
     daemons = get_daemonlist()
 
     if not daemons:
-        print 'no elbe daemons installed'
+        print("no elbe daemons installed")
 
     oparser = OptionParser(usage="usage: %prog")
     oparser.add_option( "--host", dest="host", default='0.0.0.0',
@@ -53,16 +55,16 @@ def run_command( argv ):
             if str(o) == str(d):
                 if getattr(opt,o) == True:
                     active = True
-                    print "enable", str(d)
+                    print(("enable %s" % str(d)))
                     module = "elbepack.daemons." + str(d)
                     mod = __import__(module)
                     cmdmod = sys.modules[module]
                     cherrypy.tree.graft(cmdmod.get_app(cherrypy.engine), "/"+str(d))
     if not active:
-        print 'no daemon activated, use'
+        print("no daemon activated, use")
         for d in daemons:
-            print '   --'+d
-        print 'to activate at least one daemon'
+            print(("   --%s" % d))
+        print("to activate at least one daemon")
         return
 
     cherrypy.server.unsubscribe()
diff --git a/elbepack/commands/db.py b/elbepack/commands/db.py
index d6396b6d..166dc46d 100644
--- a/elbepack/commands/db.py
+++ b/elbepack/commands/db.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,20 +16,21 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from elbepack.dbaction import DbAction
 
 def run_command (argv):
 
     if not len(argv):
-        print 'elbe db - no action given'
+        print("elbe db - no action given")
         DbAction.print_actions ()
         return
 
     try:
         DbAction (argv[0]).execute (argv[1:])
     except KeyError:
-        print 'elbe db - unknown action given'
+        print("elbe db - unknown action given")
         DbAction.print_actions ()
         return
 
diff --git a/elbepack/commands/debianize.py b/elbepack/commands/debianize.py
index 32ca7c9a..3f80d17a 100644
--- a/elbepack/commands/debianize.py
+++ b/elbepack/commands/debianize.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 
@@ -25,7 +25,7 @@ from elbepack.debianize.debianize import Debianize, DebianizeBase
 
 def run_command ( args ):
     if os.path.exists ('debian'):
-        print 'debian folder already exists, nothing to do'
+        print("debian folder already exists, nothing to do")
         sys.exit (10)
 
     try:
@@ -33,7 +33,7 @@ def run_command ( args ):
         Debianize (debianizer).run ()
         sys.exit(10)
     except KeyError:
-        print ("This creates a debinization of a source directory.")
-        print ("The software was not able to identify the current directory.")
-        print ("Please run the command from source directory")
+        print("This creates a debinization of a source directory.")
+        print("The software was not able to identify the current directory.")
+        print("Please run the command from source directory")
         sys.exit (20)
diff --git a/elbepack/commands/diff.py b/elbepack/commands/diff.py
index 0cbe7107..b6e6007c 100644
--- a/elbepack/commands/diff.py
+++ b/elbepack/commands/diff.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 import filecmp
@@ -40,7 +42,7 @@ def walk_generated( gen_path, fix_path, exclude ):
 
         if len(files)==0:
             if not os.path.exists(fix_path+infs_root):
-                print "empty directory %s only exists in gen image" % (infs_root)
+                print(("empty directory %s only exists in gen image" % (infs_root)))
                 file_to_rm.append( infs_root )
         else:
             for f in files:
@@ -51,17 +53,17 @@ def walk_generated( gen_path, fix_path, exclude ):
                     if os.path.isfile(gen_fname) and os.path.isfile(fix_fname):
                         if not os.path.islink(gen_fname) and not os.path.islink(fix_fname):
                             if not filecmp.cmp(gen_fname,fix_fname,shallow=False):
-                                print "files %s and %s differ" %(gen_fname, fix_fname)
+                                print(("files %s and %s differ" %(gen_fname, fix_fname)))
                                 file_differ.append(os.path.join( infs_root, f ) )
                         else:
                             if not (os.readlink(gen_fname) == os.readlink(fix_fname)):
-                                print "symlinks %s and %s differ" %(gen_fname, fix_fname)
+                                print(("symlinks %s and %s differ" %(gen_fname, fix_fname)))
                                 file_differ.append(os.path.join( infs_root, f ) )
 
                 elif not os.path.exists(gen_fname) and os.path.exists(fix_fname):
-                    print "file %s only exists in fixed image" % (fix_fname)
+                    print(("file %s only exists in fixed image" % (fix_fname)))
                 elif os.path.exists(gen_fname) and not os.path.exists(fix_fname):
-                    print "file %s only exists in gen image" % (gen_fname)
+                    print(("file %s only exists in gen image" % (gen_fname)))
                     file_to_rm.append( os.path.join( infs_root, f ) )
 
     return file_differ, file_to_rm
@@ -85,7 +87,7 @@ def walk_fixed( gen_path, fix_path, exclude ):
 
         if len(files)==0:
             if not os.path.exists(gen_path+infs_root):
-                print "empty directory %s only exists in fix image" % (infs_root)
+                print(("empty directory %s only exists in fix image" % (infs_root)))
                 dir_to_create.append( infs_root.lstrip("/") )
         else:
             for f in files:
@@ -93,7 +95,7 @@ def walk_fixed( gen_path, fix_path, exclude ):
                 fix_fname = os.path.join(fix_path+infs_root, f)
 
                 if not os.path.exists(gen_fname) and os.path.exists(fix_fname):
-                    print "file %s only exists in fixed image" % (fix_fname)
+                    print(("file %s only exists in fixed image" % (fix_fname)))
                     file_only.append( os.path.join( infs_root, f ) )
 
     return file_only, dir_to_create
@@ -106,7 +108,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 2:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
@@ -120,19 +122,19 @@ def run_command( argv ):
     only, mkdir = walk_fixed( gen_rfs, fix_rfs, opt.exclude )
 
 
-    print "suggesting:"
-    print
+    print("suggesting:")
+    print()
 
     for f in rm:
-        print "<rm>%s</rm>"%f
+        print(("<rm>%s</rm>"%f))
 
     for d in mkdir:
-        print "<mkdir>%s</mkdir>"%d
+        print(("<mkdir>%s</mkdir>"%d))
 
-    print
+    print("")
 
     fileline=""
     for f in differ+only:
-        print "tar rf archive.tar -C %s %s"%(fix_rfs, f)
+        print(("tar rf archive.tar -C %s %s"%(fix_rfs, f)))
 
 
diff --git a/elbepack/commands/gen_update.py b/elbepack/commands/gen_update.py
index 9aa4a000..e3cd4faa 100644
--- a/elbepack/commands/gen_update.py
+++ b/elbepack/commands/gen_update.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from optparse import OptionParser
 import sys
 
@@ -58,11 +58,11 @@ def run_command( argv ):
             sys.exit(20)
 
     if len(args) == 1 and not opt.target:
-        print "No target specified"
+        print("No target specified")
         sys.exit(20)
 
     if not opt.output:
-        print "No output file specified"
+        print("No output file specified")
         sys.exit(20)
 
     if opt.buildtype:
@@ -75,22 +75,22 @@ def run_command( argv ):
                 override_buildtype=buildtype,
                 skip_validate=opt.skip_validation)
     except ValidationError as e:
-        print str(e)
-        print "xml validation failed. Bailing out"
+        print((str(e)))
+        print("xml validation failed. Bailing out")
         sys.exit(20)
 
     if opt.presh_file:
         try:
             project.presh_file = open (opt.presh_file)
         except IOError as e:
-            print 'pre.sh file invalid: %s' % str (e)
+            print(('pre.sh file invalid: %s' % str (e)))
             sys.exit(20)
 
     if opt.postsh_file:
         try:
             project.postsh_file = open (opt.postsh_file)
         except IOError as e:
-            print 'post.sh file invalid: %s' % str (e)
+            print(('post.sh file invalid: %s' % str (e)))
             sys.exit(20)
 
     update_xml = None
@@ -103,11 +103,11 @@ def run_command( argv ):
                 cfg_dir = opt.cfg_dir, cmd_dir = opt.cmd_dir )
 
     except ValidationError as e:
-        print str(e)
-        print "xml validation failed. Bailing out"
+        print((str(e)))
+        print("xml validation failed. Bailing out")
         sys.exit(20)
     except MissingData as e:
-        print str(e)
+        print((str(e)))
         sys.exit(20)
 
     if project.postsh_file:
diff --git a/elbepack/commands/genlicence.py b/elbepack/commands/genlicence.py
index 234000f7..dfe77dc3 100644
--- a/elbepack/commands/genlicence.py
+++ b/elbepack/commands/genlicence.py
@@ -16,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from optparse import OptionParser
 import sys
@@ -35,7 +36,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "wrong number of arguments"
+        print("wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
diff --git a/elbepack/commands/get_archive.py b/elbepack/commands/get_archive.py
index cfba9825..1129e732 100644
--- a/elbepack/commands/get_archive.py
+++ b/elbepack/commands/get_archive.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,10 +16,11 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 
-
 from base64 import standard_b64decode
 
 from elbepack.treeutils import etree
@@ -40,28 +39,28 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 2:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     if os.path.exists( args[1] ):
-        print "archive already exists, bailing out"
+        print("archive already exists, bailing out")
         sys.exit(20)
 
     try:
         xml = etree( args[0] )
     except:
-        print "Error reading xml file!"
+        print("Error reading xml file!")
         sys.exit(20)
 
     if xml.has("archive"):
         try:
             unbase( xml.text("/archive"), args[1] )
         except:
-            print "Error writing archive"
+            print("Error writing archive")
             sys.exit(20)
     else:
-        print "no archive in this xml file."
+        print("no archive in this xml file.")
         sys.exit(20)
 
 
diff --git a/elbepack/commands/hdimg.py b/elbepack/commands/hdimg.py
index 05be1138..494a2bd8 100644
--- a/elbepack/commands/hdimg.py
+++ b/elbepack/commands/hdimg.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 
 from optparse import OptionParser
@@ -48,17 +48,17 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     if not opt.target:
-        print "No directory specified!"
+        print("No directory specified!")
         oparser.print_help()
         sys.exit(20)
 
     if not opt.output:
-        print "No Log output"
+        print("No Log output")
         oparser.print_help()
         sys.exit(20)
 
@@ -66,7 +66,7 @@ def run_command( argv ):
         opt.grub_version = 0
 
     if opt.grub_version not in [0,199,202]:
-        print "invalid grub version"
+        print("invalid grub version")
         oparser.print_help()
         sys.exit(20)
 
@@ -75,8 +75,8 @@ def run_command( argv ):
                 xmlpath=args[0], logpath=opt.output,
                 skip_validate=opt.skip_validation )
     except ValidationError as e:
-        print str(e)
-        print "xml validation failed. Bailing out"
+        print((str(e)))
+        print("xml validation failed. Bailing out")
         sys.exit(20)
 
     project.targetfs.part_target(opt.target, opt.grub_version)
diff --git a/elbepack/commands/init.py b/elbepack/commands/init.py
index 1a009b49..a624b835 100644
--- a/elbepack/commands/init.py
+++ b/elbepack/commands/init.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 import shutil
@@ -68,31 +68,31 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) == 0:
-        print "no filename specified"
+        print("no filename specified")
         oparser.print_help()
         sys.exit(20)
     elif len(args) > 1:
-        print "too many filenames specified"
+        print("too many filenames specified")
         oparser.print_help()
         sys.exit(20)
 
     if opt.devel:
         if not os.path.isdir( os.path.join (elbe_dir, "elbepack")):
-            print "Devel Mode only valid, when running from elbe checkout"
+            print("Devel Mode only valid, when running from elbe checkout")
             sys.exit(20)
 
     if not opt.skip_validation:
         validation = validate_xml (args[0])
         if len (validation) != 0:
-            print "xml validation failed. Bailing out"
+            print("xml validation failed. Bailing out")
             for i in validation:
-                print i
+                print(i)
             sys.exit(20)
 
     xml = etree( args[0] )
 
     if not xml.has( "initvm" ):
-        print "fatal error: xml missing mandatory section 'initvm'"
+        print("fatal error: xml missing mandatory section 'initvm'")
         sys.exit(20)
 
     if opt.buildtype:
@@ -125,15 +125,15 @@ def run_command( argv ):
 
     try:
         os.makedirs(path)
-    except OSError, e:
-        print 'unable to create project directory: %s (%s)' % (path, e.strerror)
+    except OSError as e:
+        print(("unable to create project directory: %s (%s)" % (path, e.strerror)))
         sys.exit(30)
 
     out_path = os.path.join(path,".elbe-in")
     try:
         os.makedirs(out_path)
-    except OSError, e:
-        print 'unable to create subdirectory: %s (%s)' % (out_path, e.strerror)
+    except OSError as e:
+        print(("unable to create subdirectory: %s (%s)" % (out_path, e.strerror)))
         sys.exit(30)
 
     d = {"elbe_version": elbe_version,
@@ -153,11 +153,11 @@ def run_command( argv ):
     try:
         copy_kinitrd(xml.node("/initvm"), out_path, defs, arch="amd64")
     except NoKinitrdException as e:
-        print "Failure to download kernel/initrd debian Package:"
-        print
-        print e.message
-        print
-        print "Check Mirror configuration"
+        print("Failure to download kernel/initrd debian Package:")
+        print("")
+        print((e.message))
+        print("")
+        print("Check Mirror configuration")
         sys.exit(20)
 
     templates = os.listdir( init_template_dir )
@@ -174,7 +174,7 @@ def run_command( argv ):
             write_template(os.path.join(out_path,o), os.path.join(init_template_dir, t), d, linebreak=False )
 
         if t in make_executable:
-            os.chmod( os.path.join(out_path,o), 0755 )
+            os.chmod( os.path.join(out_path,o), 0o755 )
 
     shutil.copyfile( args[0],
        os.path.join(out_path, "source.xml" ) )
diff --git a/elbepack/commands/initvm.py b/elbepack/commands/initvm.py
index f96282b5..8e4aed8a 100755
--- a/elbepack/commands/initvm.py
+++ b/elbepack/commands/initvm.py
@@ -67,7 +67,7 @@ def run_command (argv):
     args = args[2:]
 
     if len(args) < 1:
-        print ('elbe initvm - no subcommand given', file=sys.stderr)
+        print("elbe initvm - no subcommand given", file=sys.stderr)
         InitVMAction.print_actions ()
         sys.exit(20)
 
@@ -79,13 +79,13 @@ def run_command (argv):
     try:
         action = InitVMAction (args[0])
     except KeyError:
-        print ('elbe initvm - unknown subcommand', file=sys.stderr)
+        print("elbe initvm - unknown subcommand", file=sys.stderr)
         InitVMAction.print_actions ()
         sys.exit(20)
 
     try:
         action.execute (directory, opt, args[1:])
     except InitVMError as e:
-        print ('InitVM Exception', file=sys.stderr)
-        print (e, file=sys.stderr)
+        print("InitVM Exception", file=sys.stderr)
+        print(e, file=sys.stderr)
         sys.exit(5)
diff --git a/elbepack/commands/mkcdrom.py b/elbepack/commands/mkcdrom.py
index 92748134..fb20e7ec 100644
--- a/elbepack/commands/mkcdrom.py
+++ b/elbepack/commands/mkcdrom.py
@@ -61,7 +61,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print ("wrong number of arguments", file=sys.stderr)
+        print("wrong number of arguments", file=sys.stderr)
         oparser.print_help()
         sys.exit(20)
 
@@ -71,8 +71,8 @@ def run_command( argv ):
                     override_buildtype=opt.buildtype,
                     skip_validate=opt.skip_validation )
         except ValidationError as e:
-            print (str (e), file=sys.stderr)
-            print ("xml validation failed. Bailing out", file=sys.stderr)
+            print(str (e), file=sys.stderr)
+            print("xml validation failed. Bailing out", file=sys.stderr)
             sys.exit(20)
 
         builddir = project.builddir
@@ -107,10 +107,10 @@ def run_command( argv ):
                                                 init_codename, xml, builddir, log,
                     opt.cdrom_size )
 
-    print ("")
-    print ("Image Build finished !")
-    print ("")
-    print ("Files generated:")
+    print("")
+    print("Image Build finished !")
+    print("")
+    print("Files generated:")
     for f in generated_files:
-        print (" %s"%f)
+        print(" %s"%f)
 
diff --git a/elbepack/commands/parselicence.py b/elbepack/commands/parselicence.py
index 708d5aa4..2d63030d 100644
--- a/elbepack/commands/parselicence.py
+++ b/elbepack/commands/parselicence.py
@@ -16,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from optparse import OptionParser
 from datetime import datetime
@@ -56,16 +57,16 @@ class license_dep5_to_spdx (dict):
 
 
     def have_override (self, pkgname):
-        return self.perpackage_override.has_key (pkgname)
+        return pkgname in self.perpackage_override
 
     def get_override (self, pkgname):
         return self.perpackage_override[pkgname]
 
     def map_one_license (self, pkgname, l, errors):
-        if self.perpackage_mapping.has_key(pkgname):
-            if self.perpackage_mapping[pkgname].has_key(l):
+        if pkgname in self.perpackage_mapping:
+            if l in self.perpackage_mapping[pkgname]:
                 return self.perpackage_mapping[pkgname][l]
-        if self.has_key(l):
+        if l in self:
             return self[l]
         errors.append ('no mapping for "%s" for pkg "%s"' % (l, pkgname))
         return None
@@ -78,21 +79,23 @@ class license_dep5_to_spdx (dict):
                 with_split = one_and.split (' with ')
                 mapped_lic = self.map_one_license (pkgname, with_split[0], errors)
                 if mapped_lic is None:
-                    mapped_lic = u"UNKNOWN_MAPPING(%s)" % with_split[0]
+                    mapped_lic = "UNKNOWN_MAPPING(%s)" % with_split[0]
                 if len (with_split) == 2:
-                    ands.append (mapped_lic + u" WITH " + with_split[1])
+                    ands.append (mapped_lic + " WITH " + with_split[1])
                 else:
                     ands.append (mapped_lic)
+
             ors.append (str(' AND ').join (ands))
 
         retval = str(' OR ').join (ors)
+
         return retval
 
 
 
 
     def map_lic (self, pkgname, licenses, errors):
-        if self.perpackage_override.has_key (pkgname):
+        if pkgname in self.perpackage_override:
             if len(self.perpackage_override[pkgname]) > 0:
                 return self.perpackage_override[pkgname]
 
@@ -160,7 +163,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "wrong number of arguments"
+        print("wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
@@ -172,7 +175,7 @@ def run_command( argv ):
     err_pkg = 0
 
     if not opt.mapping:
-        print "A mapping file is required"
+        print("A mapping file is required")
         oparser.print_help()
         sys.exit(20)
 
@@ -247,34 +250,34 @@ def run_command( argv ):
 
     if not opt.tagvalue is None:
         with io.open (opt.tagvalue, "wt", encoding='utf-8') as fp:
-            fp.write (u'SPDXVersion: SPDX-1.2\n')
-            fp.write (u'DataLicense: CC0-1.0\n')
+            fp.write ('SPDXVersion: SPDX-1.2\n')
+            fp.write ('DataLicense: CC0-1.0\n')
             #fp.write (u'SPDXID: SPDXRef-DOCUMENT\n')
             #fp.write (u'DocumentName: %s\n' % opt.tagvalue)
             #fp.write (u'DocumentNamespace: %s\n' % some_uri_with_uuid )
-            fp.write (u'\n')
-            fp.write (u'## Creation Information\n')
-            fp.write (u'Creator: Tool: elbe-%s\n' % elbe_version )
-            fp.write (u'Created: %s\n' % datetime.now().isoformat() )
-            fp.write (u'\n' )
-            fp.write (u'\n' )
-            fp.write (u'## Package Information\n' )
-            fp.write (u'\n' )
+            fp.write ('\n')
+            fp.write ('## Creation Information\n')
+            fp.write ('Creator: Tool: elbe-%s\n' % elbe_version )
+            fp.write ('Created: %s\n' % datetime.now().isoformat() )
+            fp.write ('\n' )
+            fp.write ('\n' )
+            fp.write ('## Package Information\n' )
+            fp.write ('\n' )
 
             for pkg in tree.root:
-                fp.write (u'## Package %s\n' % pkg.et.attrib['name'] )
-                fp.write (u'PackageName: %s\n' % pkg.et.attrib['name'])
-                fp.write (u'PackageDownloadLocation: NOASSERTION\n')
+                fp.write ('## Package %s\n' % pkg.et.attrib['name'] )
+                fp.write ('PackageName: %s\n' % pkg.et.attrib['name'])
+                fp.write ('PackageDownloadLocation: NOASSERTION\n')
                 #fp.write (u'PackageVerificationCode: %s\n')
                 if pkg.has ('have_override'):
-                    fp.write (u'PackageLicenseConcluded: %s\n' % license_string (pkg))
-                    fp.write (u'PackageLicenseDeclared: NOASSERTION\n')
+                    fp.write ('PackageLicenseConcluded: %s\n' % license_string (pkg))
+                    fp.write ('PackageLicenseDeclared: NOASSERTION\n')
 
                 else:
-                    fp.write (u'PackageLicenseConcluded: NOASSERTION\n')
-                    fp.write (u'PackageLicenseDeclared: %s\n' % license_string (pkg))
-                fp.write (u'PackageLicenseInfoFromFiles: NOASSERTION\n')
-                fp.write (u'\n' )
+                    fp.write ('PackageLicenseConcluded: NOASSERTION\n')
+                    fp.write ('PackageLicenseDeclared: %s\n' % license_string (pkg))
+                fp.write ('PackageLicenseInfoFromFiles: NOASSERTION\n')
+                fp.write ('\n' )
 
 
 
@@ -283,8 +286,8 @@ def run_command( argv ):
         tree.write (opt.output)
 
 
-    print "statistics:"
-    print 'num:%d mr:%d hr:%d err_pkg:%d' % (num_pkg, mr, hr, err_pkg)
+    print("statistics:")
+    print(("num:%d mr:%d hr:%d err_pkg:%d" % (num_pkg, mr, hr, err_pkg)))
 
 
 
diff --git a/elbepack/commands/pbuilder.py b/elbepack/commands/pbuilder.py
index 2f8b94ab..6af87737 100755
--- a/elbepack/commands/pbuilder.py
+++ b/elbepack/commands/pbuilder.py
@@ -50,20 +50,20 @@ def run_command (argv):
     args = args[2:]
 
     if len(args) < 1:
-        print ('elbe pbuilder - no subcommand given', file=sys.stderr)
+        print("elbe pbuilder - no subcommand given", file=sys.stderr)
         PBuilderAction.print_actions ()
         return
 
     try:
         action = PBuilderAction (args[0])
     except KeyError:
-        print ('elbe pbuilder - unknown subcommand', file=sys.stderr)
+        print("elbe pbuilder - unknown subcommand", file=sys.stderr)
         PBuilderAction.print_actions ()
         sys.exit(20)
 
     try:
         action.execute (opt, args[1:])
     except PBuilderError as e:
-        print ('PBuilder Exception', file=sys.stderr)
-        print (e, file=sys.stderr)
+        print("PBuilder Exception", file=sys.stderr)
+        print(e, file=sys.stderr)
         sys.exit(5)
diff --git a/elbepack/commands/pin_versions.py b/elbepack/commands/pin_versions.py
index 2b4b83b6..e4bdf671 100644
--- a/elbepack/commands/pin_versions.py
+++ b/elbepack/commands/pin_versions.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 
 from elbepack.treeutils import etree
@@ -35,26 +35,26 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     if not opt.skip_validation:
         validation = validate_xml (args[0])
         if len (validation) != 0:
-            print "xml validation failed. Bailing out"
+            print("xml validation failed. Bailing out")
             for i in validation:
-                print i
+                print(i)
             sys.exit(20)
 
     try:
         xml = etree( args[0] )
     except:
-        print "Error reading xml file!"
+        print("Error reading xml file!")
         sys.exit(20)
 
     if not xml.has ("fullpkgs"):
-        print "xml file does not have fullpkgs node"
+        print("xml file does not have fullpkgs node")
         sys.exit(20)
 
     plist = xml.ensure_child("/target/pkg-list")
@@ -74,6 +74,6 @@ def run_command( argv ):
     try:
         xml.write( args[0] )
     except:
-        print "Unable to write new xml file"
+        print("Unable to write new xml file")
         sys.exit(20)
 
diff --git a/elbepack/commands/pkgdiff.py b/elbepack/commands/pkgdiff.py
index ec14f017..de971544 100644
--- a/elbepack/commands/pkgdiff.py
+++ b/elbepack/commands/pkgdiff.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import sys
 
@@ -34,7 +36,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 2:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
@@ -77,16 +79,16 @@ def run_command( argv ):
             if p.current_ver and not p.essential:
                 fix_pkgs[p.name] = p.current_ver
 
-    for p in fix_pkgs.keys():
-        if not p in gen_pkgs.keys():
-            print "+<pkg>%s</pkg>" % p
+    for p in list(fix_pkgs.keys()):
+        if not p in list(gen_pkgs.keys()):
+            print(("+<pkg>%s</pkg>" % p))
 
-    for p in gen_pkgs.keys():
-        if not p in fix_pkgs.keys():
-            print "-<pkg>%s</pkg>" % p
+    for p in list(gen_pkgs.keys()):
+        if not p in list(fix_pkgs.keys()):
+            print(("-<pkg>%s</pkg>" % p))
 
-    for p in fix_pkgs.keys():
-        if p in gen_pkgs.keys() and fix_pkgs[p] != gen_pkgs[p]:
-            print "%s: Version mismatch %s != %s" % (p, fix_pkgs[p], gen_pkgs[p])
+    for p in list(fix_pkgs.keys()):
+        if p in list(gen_pkgs.keys()) and fix_pkgs[p] != gen_pkgs[p]:
+            print(("%s: Version mismatch %s != %s" % (p, fix_pkgs[p], gen_pkgs[p])))
 
 
diff --git a/elbepack/commands/prjrepo.py b/elbepack/commands/prjrepo.py
index 76f12bdc..88b6bf02 100755
--- a/elbepack/commands/prjrepo.py
+++ b/elbepack/commands/prjrepo.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2017  Linutronix GmbH
 #
@@ -20,13 +18,22 @@
 
 from __future__ import print_function
 
+#different module names in python 2 and 3
+try:
+    from urllib.error import URLError
+except ImportError:
+    from urllib2 import URLError
+
+try:
+    from httplib2 import BadStatusLine
+except ImportError:
+    from httplib import BadStatusLine
+
 import socket
 import sys
 
 from optparse import (OptionParser, OptionGroup)
 from suds import WebFault
-from urllib2 import URLError
-from httplib import BadStatusLine
 
 from elbepack.soapclient import RepoAction, ElbeSoapClient
 from elbepack.version import elbe_version
@@ -71,7 +78,7 @@ def run_command(argv):
     args = args[2:]
 
     if len(args) < 1:
-        print ('elbe prjrepo - no subcommand given', file=sys.stderr)
+        print("elbe prjrepo - no subcommand given", file=sys.stderr)
         RepoAction.print_actions()
         return
 
@@ -86,27 +93,27 @@ def run_command(argv):
             retries=int(
                 opt.retries))
     except socket.error as e:
-        print ("Failed to connect to Soap server %s:%s\n" %
+        print("Failed to connect to Soap server %s:%s\n" %
                (opt.host, opt.port), file=sys.stderr)
-        print ("", file=sys.stderr)
-        print (
+        print("", file=sys.stderr)
+        print(
             "Check, wether the Soap Server is running inside the initvm",
             file=sys.stderr)
-        print ("try 'elbe initvm attach'", file=sys.stderr)
+        print("try 'elbe initvm attach'", file=sys.stderr)
         sys.exit(10)
     except URLError as e:
-        print ("Failed to connect to Soap server %s:%s\n" %
+        print("Failed to connect to Soap server %s:%s\n" %
                (opt.host, opt.port), file=sys.stderr)
-        print ("", file=sys.stderr)
-        print ("Check, wether the initvm is actually running.", file=sys.stderr)
-        print ( "try `elbe initvm start`", file=sys.stderr)
+        print("", file=sys.stderr)
+        print("Check, wether the initvm is actually running.", file=sys.stderr)
+        print( "try `elbe initvm start`", file=sys.stderr)
         sys.exit(10)
     except BadStatusLine as e:
-        print ("Failed to connect to Soap server %s:%s\n" %
+        print("Failed to connect to Soap server %s:%s\n" %
                (opt.host, opt.port), file=sys.stderr)
-        print ("", file=sys.stderr)
-        print ("Check, wether the initvm is actually running.", file=sys.stderr)
-        print (
+        print("", file=sys.stderr)
+        print("Check, wether the initvm is actually running.", file=sys.stderr)
+        print(
             "try 'elbe initvm --directory /path/to/initvm start'",
             file=sys.stderr)
         sys.exit(10)
@@ -115,13 +122,13 @@ def run_command(argv):
     try:
         v_server = control.service.get_version ()
         if v_server != elbe_version:
-            print ("elbe v%s is used in initvm, this is not compatible with \
+            print("elbe v%s is used in initvm, this is not compatible with \
 elbe v%s that is used on this machine. Please install same \
 versions of elbe in initvm and on your machine." % (v_server, elbe_version), file=sys.stderr)
             if not (opt.ignore_version):
                 sys.exit (20)
     except AttributeError:
-        print ("the elbe installation inside the initvm doesn't provide a \
+        print("the elbe installation inside the initvm doesn't provide a \
 get_version interface. Please create a new initvm or upgrade \
 elbe inside the existing initvm.", file=sys.stderr)
         if not (opt.ignore_version):
@@ -131,7 +138,7 @@ elbe inside the existing initvm.", file=sys.stderr)
     try:
         action = RepoAction(args[0])
     except KeyError:
-        print ('elbe prjrepo - unknown subcommand', file=sys.stderr)
+        print("elbe prjrepo - unknown subcommand", file=sys.stderr)
         RepoAction.print_actions()
         sys.exit(20)
 
@@ -139,10 +146,10 @@ elbe inside the existing initvm.", file=sys.stderr)
     try:
         action.execute(control, opt, args[1:])
     except WebFault as e:
-        print ('Server returned error:', file=sys.stderr)
-        print ('', file=sys.stderr)
+        print("Server returned an error:", file=sys.stderr)
+        print("", file=sys.stderr)
         if hasattr(e.fault, 'faultstring'):
-            print (e.fault.faultstring, file=sys.stderr)
+            print(e.fault.faultstring, file=sys.stderr)
         else:
-            print (e, file=sys.stderr)
+            print(e, file=sys.stderr)
         sys.exit(5)
diff --git a/elbepack/commands/remove_sign.py b/elbepack/commands/remove_sign.py
index b2b58eee..0da802e5 100644
--- a/elbepack/commands/remove_sign.py
+++ b/elbepack/commands/remove_sign.py
@@ -20,16 +20,18 @@
 # with has to have ultimate trust level, otherwise you'll only get
 # VALID (Untrusted)!
 
+from __future__ import print_function
+
 from elbepack.gpg import unsign_file
 
 def run_command( argv ):
     if(len(argv) != 1):
-        print 'Wrong number of arguments.'
-        print 'Please pass the name of the file to unsign.'
+        print("Wrong number of arguments.")
+        print("Please pass the name of the file to unsign.")
         return
 
     fname = unsign_file( argv[0] )
     if fname:
-        print "unsigned file:", fname
+        print(("unsigned file: %s" % fname))
     else:
-        print "removing signature failed"
+        print("removing signature failed")
diff --git a/elbepack/commands/setsel.py b/elbepack/commands/setsel.py
index 799116db..160d8f76 100644
--- a/elbepack/commands/setsel.py
+++ b/elbepack/commands/setsel.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,8 +16,9 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
-import sys
+from __future__ import print_function
 
+import sys
 
 from elbepack.treeutils import etree
 from optparse import OptionParser
@@ -38,12 +37,12 @@ def parse_selections( fname ):
         sp = l.split()
 
 
-        print sp[0], sp[1]
+        print(("%s %s" % (sp[0], sp[1])))
 
         if sp[1] == 'install':
             sels.append(sp[0])
 
-    print sels
+    print(sels)
     return sels
 
 
@@ -53,7 +52,7 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 2:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
diff --git a/elbepack/commands/show.py b/elbepack/commands/show.py
index 1a02155b..cb95e50d 100644
--- a/elbepack/commands/show.py
+++ b/elbepack/commands/show.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 
 from elbepack.treeutils import etree
@@ -39,12 +39,12 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) == 0:
-        print "No Filename specified"
+        print("No Filename specified")
         oparser.print_help()
         sys.exit(20)
 
     if len(args) > 1:
-        print "too many filenames specified"
+        print("too many filenames specified")
         oparser.print_help()
         sys.exit(20)
 
@@ -52,39 +52,39 @@ def run_command( argv ):
         if not opt.skip_validation:
             validation = validate_xml (args[0])
             if len (validation) != 0:
-                print "xml validation failed. Bailing out"
+                print("xml validation failed. Bailing out")
                 for i in validation:
-                    print i
+                    print(i)
                 sys.exit(20)
 
         xml = etree( args[0] )
     except:
-        print "Unable to open xml File. Bailing out"
+        print("Unable to open xml File. Bailing out")
         sys.exit(20)
 
     if not xml.has("./project"):
-        print "no project description available"
+        print("no project description available")
         sys.exit(20)
 
-    print '== %s ==' %(args[0])
-    print 'Debian suite: %s' % (xml.text("./project/suite"))
+    print(("== %s ==" %(args[0])))
+    print(("Debian suite: %s" % (xml.text("./project/suite"))))
     for s in xml.text("./project/description").splitlines():
-        print '%s' % s.strip()
+        print(("%s" % s.strip()))
     if opt.verbose:
-        print 'root password: %s' % xml.text("./target/passwd")
-        print 'primary_mirror: %s://%s%s' %(
+        print(("root password: %s" % xml.text("./target/passwd")))
+        print(("primary_mirror: %s://%s%s" % (
               xml.text("./project/mirror/primary_proto"),
               xml.text("./project/mirror/primary_host"),
-              xml.text("./project/mirror/primary_path"))
+              xml.text("./project/mirror/primary_path"))))
         if xml.has("./project/mirror/url-list"):
-            print 'additional mirrors:'
+            print("additional mirrors:")
             for url in xml.node("./project/mirror/url-list"):
                 if url.has("binary"):
-                    print '    deb %s' % url.text("binary").strip()
+                    print(("    deb %s" % url.text("binary").strip()))
                 if url.has("source"):
-                    print '    deb-src %s' % url.text("source").strip()
-        print 'packages:'
+                    print(("    deb-src %s" % url.text("source").strip()))
+        print("packages:")
         for pkg in xml.node("./target/pkg-list"):
-            print '    %s' % pkg.et.text
-        print 'skip package validation: %s' % xml.has("./project/noauth")
-        print 'archive embedded?        %s' % xml.has("./archive")
+            print(("    %s" % pkg.et.text))
+        print(("skip package validation: %s" % xml.has("./project/noauth")))
+        print(("archive embedded?        %s" % xml.has("./archive")))
diff --git a/elbepack/commands/sign.py b/elbepack/commands/sign.py
index b87c9849..4047352b 100644
--- a/elbepack/commands/sign.py
+++ b/elbepack/commands/sign.py
@@ -16,12 +16,14 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from elbepack.gpg import sign_file
 
 def run_command( argv ):
     if(len(argv) != 2):
-        print 'Wrong number of arguments.'
-        print 'Please pass the name of the file to sign and a valid gnupg fingerprint.'
+        print("Wrong number of arguments.")
+        print("Please pass the name of the file to sign and a valid gnupg fingerprint.")
         return
     else:
         sign_file( argv[0], argv[1])
diff --git a/elbepack/commands/toolchainextract.py b/elbepack/commands/toolchainextract.py
index bbf4e163..5fc150c4 100644
--- a/elbepack/commands/toolchainextract.py
+++ b/elbepack/commands/toolchainextract.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from optparse import OptionParser
 from tempfile import mkdtemp
 
diff --git a/elbepack/commands/updated.py b/elbepack/commands/updated.py
index 0eb25b6b..2cde1ad4 100644
--- a/elbepack/commands/updated.py
+++ b/elbepack/commands/updated.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 # Copyright (C) 2015  emtrion GmbH
@@ -19,6 +17,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import signal
 import sys
diff --git a/elbepack/commands/validate.py b/elbepack/commands/validate.py
index 99a6368b..a3e9d58f 100644
--- a/elbepack/commands/validate.py
+++ b/elbepack/commands/validate.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 import os
 from optparse import OptionParser
@@ -35,22 +37,22 @@ def run_command( argv ):
         sys.exit(20)
 
     if not os.path.exists(args[2]):
-        print ("%s - file not found" % args[2])
+        print(("%s - file not found" % args[2]))
         oparser.print_help()
         sys.exit(20)
 
     validation = validate_xml (args[2])
     if len (validation):
-        print "validation failed"
+        print("validation failed")
         for i in validation:
-            print i
+            print(i)
         sys.exit(20)
 
     if opt.validate_urls:
         try:
             xml = ElbeXML(args[2], url_validation=ValidationMode.CHECK_ALL)
         except ValidationError as e:
-            print e
+            print(e)
             sys.exit(20)
 
     sys.exit (0)
diff --git a/elbepack/commands/xsdtoasciidoc.py b/elbepack/commands/xsdtoasciidoc.py
index c64e11c4..ec3e172e 100644
--- a/elbepack/commands/xsdtoasciidoc.py
+++ b/elbepack/commands/xsdtoasciidoc.py
@@ -18,6 +18,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 
 from elbepack.treeutils import etree
@@ -36,14 +38,14 @@ def run_command( argv ):
     (opt,args) = oparser.parse_args(argv)
 
     if len(args) != 1:
-        print "Wrong number of arguments"
+        print("Wrong number of arguments")
         oparser.print_help()
         sys.exit(20)
 
     xml = etree( args[0] )
 
     if not opt.out:
-        print 'output is mandatory'
+        print("--output is mandatory")
         sys.exit(20)
 
     d = {"opt": opt,
diff --git a/elbepack/config.py b/elbepack/config.py
index 08aa9fa3..b2b633d5 100644
--- a/elbepack/config.py
+++ b/elbepack/config.py
@@ -1,4 +1,3 @@
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -17,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 
 class Config(dict):
@@ -27,7 +28,7 @@ class Config(dict):
         self['passwd']   = "foo"
         self['pbuilder_jobs'] = "auto"
 
-        if os.environ.has_key('ELBE_SOAPPORT'):
+        if 'ELBE_SOAPPORT' in os.environ:
             self['soapport'] = os.environ['ELBE_SOAPPORT']
 
         if 'ELBE_SOAPHOST' in os.environ:
diff --git a/elbepack/daemons/soap/__init__.py b/elbepack/daemons/soap/__init__.py
index 623f76f8..761501af 100644
--- a/elbepack/daemons/soap/__init__.py
+++ b/elbepack/daemons/soap/__init__.py
@@ -16,13 +16,32 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
-from esoap import ESoap
+from __future__ import print_function
 
-from beaker.middleware import SessionMiddleware
+import sys
 
-from spyne import Application
-from spyne.protocol.soap import Soap11
-from spyne.server.wsgi import WsgiApplication
+# enable packaging of python3-elbe-common even if python3-spyne is
+# not available atm.
+try:
+    from .esoap import ESoap
+except ImportError as e:
+    print ("failed to import esoap", file=sys.stderr)
+
+try:
+    from beaker.middleware import SessionMiddleware
+except ImportError as e:
+    print ("failed to import beaker", file=sys.stderr)
+    class SessionMiddleware:
+        pass
+
+try:
+    from spyne import Application
+    from spyne.protocol.soap import Soap11
+    from spyne.server.wsgi import WsgiApplication
+except ImportError as e:
+    class Application:
+        pass
+    print ("failed to import spyne", file=sys.stderr)
 
 from cherrypy.process.plugins import SimplePlugin
 
diff --git a/elbepack/daemons/soap/authentication.py b/elbepack/daemons/soap/authentication.py
index 9cb14440..e88da1c5 100644
--- a/elbepack/daemons/soap/authentication.py
+++ b/elbepack/daemons/soap/authentication.py
@@ -16,9 +16,9 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
-
-from faults import SoapElbeNotLoggedIn, SoapElbeNotAuthorized
+from .faults import SoapElbeNotLoggedIn, SoapElbeNotAuthorized
 from functools import wraps
 
 def authenticated_uid(func):
@@ -32,7 +32,7 @@ def authenticated_uid(func):
             @authenticated_uid
             def get_files (self, uid, builddir): 
     """
-    if func.func_code.co_argcount == 2:
+    if func.__code__.co_argcount == 2:
         @wraps(func)
         def wrapped(self):
             s = self.transport.req_env['beaker.session']
@@ -43,7 +43,7 @@ def authenticated_uid(func):
 
             return func(self,uid)
         return wrapped
-    elif func.func_code.co_argcount == 3:
+    elif func.__code__.co_argcount == 3:
         @wraps(func)
         def wrapped(self, arg1):
             s = self.transport.req_env['beaker.session']
@@ -54,7 +54,7 @@ def authenticated_uid(func):
 
             return func(self,uid,arg1)
         return wrapped
-    elif func.func_code.co_argcount == 4:
+    elif func.__code__.co_argcount == 4:
         @wraps(func)
         def wrapped(self, arg1, arg2):
             s = self.transport.req_env['beaker.session']
@@ -65,7 +65,7 @@ def authenticated_uid(func):
 
             return func(self,uid,arg1,arg2)
         return wrapped
-    elif func.func_code.co_argcount == 5:
+    elif func.__code__.co_argcount == 5:
         @wraps(func)
         def wrapped(self, arg1, arg2, arg3):
             s = self.transport.req_env['beaker.session']
@@ -76,7 +76,7 @@ def authenticated_uid(func):
 
             return func(self,uid,arg1,arg2,arg3)
         return wrapped
-    elif func.func_code.co_argcount == 6:
+    elif func.__code__.co_argcount == 6:
         @wraps(func)
         def wrapped(self, arg1, arg2, arg3, arg4):
             s = self.transport.req_env['beaker.session']
@@ -87,7 +87,7 @@ def authenticated_uid(func):
 
             return func(self,uid,arg1,arg2,arg3,arg4)
         return wrapped
-    elif func.func_code.co_argcount == 7:
+    elif func.__code__.co_argcount == 7:
         @wraps(func)
         def wrapped(self, arg1, arg2, arg3, arg4, arg5):
             s = self.transport.req_env['beaker.session']
@@ -99,7 +99,7 @@ def authenticated_uid(func):
             return func(self,uid,arg1,arg2,arg3,arg4,arg5)
         return wrapped
     else:
-        raise Exception( "arg count %d not implemented" % func.func_code.co_argcount )
+        raise Exception( "arg count %d not implemented" % func.__code__.co_argcount )
 
 
 
@@ -114,7 +114,7 @@ def authenticated_admin(func):
             @authenticated_uid
             def get_files (self, uid, builddir): 
     """
-    if func.func_code.co_argcount == 1:
+    if func.__code__.co_argcount == 1:
         @wraps(func)
         def wrapped(self):
             s = self.transport.req_env['beaker.session']
@@ -127,7 +127,7 @@ def authenticated_admin(func):
                 raise SoapElbeNotAuthorized()
             return func(self)
         return wrapped
-    elif func.func_code.co_argcount == 2:
+    elif func.__code__.co_argcount == 2:
         @wraps(func)
         def wrapped(self, arg1):
             s = self.transport.req_env['beaker.session']
@@ -141,7 +141,7 @@ def authenticated_admin(func):
 
             return func(self,arg1)
         return wrapped
-    elif func.func_code.co_argcount == 3:
+    elif func.__code__.co_argcount == 3:
         @wraps(func)
         def wrapped(self, arg1, arg2):
             s = self.transport.req_env['beaker.session']
@@ -155,4 +155,4 @@ def authenticated_admin(func):
             return func(self,arg1,arg2)
         return wrapped
     else:
-        raise Exception( "arg count %d not implemented" % func.func_code.co_argcount )
+        raise Exception( "arg count %d not implemented" % func.__code__.co_argcount )
diff --git a/elbepack/daemons/soap/datatypes.py b/elbepack/daemons/soap/datatypes.py
index 656ebbb7..b0d00769 100644
--- a/elbepack/daemons/soap/datatypes.py
+++ b/elbepack/daemons/soap/datatypes.py
@@ -16,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from spyne.model.complex import ComplexModel
 from spyne.model.primitive import Unicode, DateTime
diff --git a/elbepack/daemons/soap/esoap.py b/elbepack/daemons/soap/esoap.py
index 8189a94f..d0e07774 100644
--- a/elbepack/daemons/soap/esoap.py
+++ b/elbepack/daemons/soap/esoap.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,26 +16,37 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import binascii
 import os
 import tarfile
 import fnmatch
+import sys
 
 from tempfile import NamedTemporaryFile
 
 from elbepack.shellhelper import system
 from elbepack.version import elbe_version
 
-from faults import soap_faults
+try:
+    from .faults import soap_faults
+except ImportError as e:
+    print ("failed to import soap_faults", file=sys.stderr)
+    raise e
 
 from elbepack.elbexml import ValidationMode
-from datatypes import SoapProject, SoapFile
-from authentication import authenticated_admin, authenticated_uid
-
-from spyne.service import ServiceBase
-from spyne.decorator import rpc
-from spyne.model.primitive import String, Boolean, Integer
-from spyne.model.complex import Array
+from .datatypes import SoapProject, SoapFile
+from .authentication import authenticated_admin, authenticated_uid
+
+try:
+    from spyne.service import ServiceBase
+    from spyne.decorator import rpc
+    from spyne.model.primitive import String, Boolean, Integer
+    from spyne.model.complex import Array
+except ImportError as e:
+    print ("failed to import spyne", file=sys.stderr)
+    raise e
 
 class ESoap (ServiceBase):
 
diff --git a/elbepack/daemons/soap/faults.py b/elbepack/daemons/soap/faults.py
index ee80bfbe..4dc0fb29 100644
--- a/elbepack/daemons/soap/faults.py
+++ b/elbepack/daemons/soap/faults.py
@@ -16,7 +16,16 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
-from spyne.model.fault import Fault
+from __future__ import print_function
+
+import sys
+
+try:
+    from spyne.model.fault import Fault
+except ImportError as e:
+    print ("python*-spyne is not installed", file=sys.stderr)
+    raise e
+
 from traceback import format_exc
 
 from functools import wraps
@@ -61,7 +70,7 @@ def soap_faults(func):
     """ decorator, which wraps Exceptions to the proper
         Soap Faults, and raises these.
     """
-    if func.func_code.co_argcount == 1:
+    if func.__code__.co_argcount == 1:
         @wraps(func)
         def wrapped(self):
             try:
@@ -81,7 +90,7 @@ def soap_faults(func):
             except Exception as e:
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
-    if func.func_code.co_argcount == 2:
+    if func.__code__.co_argcount == 2:
         @wraps (func)
         def wrapped (self, arg1):
             try:
@@ -101,7 +110,7 @@ def soap_faults(func):
             except Exception as e:
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
-    if func.func_code.co_argcount == 3:
+    if func.__code__.co_argcount == 3:
         @wraps (func)
         def wrapped (self, arg1, arg2):
             try:
@@ -121,7 +130,7 @@ def soap_faults(func):
             except Exception as e:
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
-    if func.func_code.co_argcount == 4:
+    if func.__code__.co_argcount == 4:
         @wraps (func)
         def wrapped (self, arg1, arg2, arg3):
             try:
@@ -141,7 +150,7 @@ def soap_faults(func):
             except Exception as e:
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
-    if func.func_code.co_argcount == 5:
+    if func.__code__.co_argcount == 5:
         @wraps (func)
         def wrapped (self, arg1, arg2, arg3, arg4):
             try:
@@ -161,7 +170,7 @@ def soap_faults(func):
             except Exception as e:
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
-    if func.func_code.co_argcount == 6:
+    if func.__code__.co_argcount == 6:
         @wraps (func)
         def wrapped (self, arg1, arg2, arg3, arg4, arg5):
             try:
@@ -181,7 +190,7 @@ def soap_faults(func):
             except Exception as e:
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
-    if func.func_code.co_argcount == 7:
+    if func.__code__.co_argcount == 7:
         @wraps (func)
         def wrapped (self, arg1, arg2, arg3, arg4, arg5, arg6):
             try:
@@ -202,5 +211,5 @@ def soap_faults(func):
                 raise SoapElbeProjectError (format_exc ())
         return wrapped
     else:
-        raise Exception( "arg count %d not implemented" % func.func_code.co_argcount )
+        raise Exception( "arg count %d not implemented" % func.__code__.co_argcount )
 
diff --git a/elbepack/db.py b/elbepack/db.py
index baf4c091..2798cdc4 100644
--- a/elbepack/db.py
+++ b/elbepack/db.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,14 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
+# module name missmatch in python 2 and 3
+try:
+    from urllib.parse import quote
+except ImportError:
+    from urllib import quote
+
 import os
 import errno
 import re
@@ -25,7 +31,6 @@ import re
 from datetime import datetime
 from shutil import (rmtree, copyfile, copyfileobj)
 from contextlib import contextmanager
-from urllib import quote
 from threading import Thread
 
 from passlib.hash import pbkdf2_sha512
@@ -145,7 +150,7 @@ class ElbeDB(object):
             with open (builddir+"/postbuild.sh", 'w') as dst:
                 copyfileobj (postbuild_file, dst)
 
-            os.chmod (builddir+"/postbuild.sh", 0755)
+            os.chmod (builddir+"/postbuild.sh", 0o755)
             dos2unix (builddir+"/postbuild.sh")
 
             return self._update_project_file( s, builddir, "postbuild.sh",
@@ -179,7 +184,7 @@ class ElbeDB(object):
             with open (builddir+"/save.sh", 'w') as dst:
                 copyfileobj (savesh_file, dst)
 
-            os.chmod (builddir+"/save.sh", 0755)
+            os.chmod (builddir+"/save.sh", 0o755)
             dos2unix (builddir+"/save.sh")
 
             return self._update_project_file( s, builddir, "save.sh",
@@ -973,7 +978,7 @@ class ElbeDB(object):
             try:
                 os.makedirs (cls.db_path)
             except OSError as e:
-                print e
+                print((str(e)))
                 return
 
         db = ElbeDB()
@@ -981,7 +986,7 @@ class ElbeDB(object):
         try:
             db.add_user(name, fullname, password, email, admin)
         except ElbeDBError as e:
-            print e
+            print((str(e)))
 
 
 class User(Base):
diff --git a/elbepack/dbaction.py b/elbepack/dbaction.py
index ba65814d..c6c90e42 100644
--- a/elbepack/dbaction.py
+++ b/elbepack/dbaction.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 
 from optparse import OptionParser
@@ -36,9 +36,9 @@ class DbAction(object):
 
     @classmethod
     def print_actions(cls):
-        print 'available actions are:'
+        print("available actions are:")
         for a in cls.actiondict:
-            print '   ' + a
+            print(("   %s" % a))
 
     def __new__(cls, node):
         action = cls.actiondict[node]
@@ -86,7 +86,7 @@ class AddUserAction(DbAction):
         (opt, arg) = oparser.parse_args (args)
 
         if len(arg) != 1:
-            print "wrong number of arguments"
+            print("wrong number of arguments")
             oparser.print_help()
             return
 
@@ -116,13 +116,13 @@ class DelUserAction(DbAction):
         (opt, arg) = oparser.parse_args (args)
 
         if len(arg) != 1:
-            print "usage: elbe db del_user <userid>"
+            print("usage: elbe db del_user <userid>")
             return
 
         try:
             userid = int(arg[0])
         except:
-            print "userid must be an integer"
+            print("userid must be an integer")
             return
 
         db = ElbeDB()
@@ -132,18 +132,18 @@ class DelUserAction(DbAction):
         if projects:
             if not opt.quiet:
                 if opt.delete_projects:
-                    print "removing projects owned by the deleted user:"
+                    print("removing projects owned by the deleted user:")
                 else:
-                    print "keeping projects owned by the deleted user:"
+                    print("keeping projects owned by the deleted user:")
 
         for p in projects:
             if not opt.quiet:
-                print p.builddir + ":", p.name, "[", p.version, "]", p.edit
+                print(("%s: %s [%s] %s" % (p.builddir, p.name, p.version, p.edit)))
             if opt.delete_projects:
                 try:
                     db.del_project( p.builddir )
                 except ElbeDBError as e:
-                    print "  ==> ", e
+                    print(("  ==> %s " % str(e)))
 
 DbAction.register(DelUserAction)
 
@@ -159,7 +159,7 @@ class ListProjectsAction(DbAction):
         projects = db.list_projects ()
 
         for p in projects:
-            print p.builddir+":", p.name, "[", p.version, "]", p.edit
+            print(("%s: %s [%s] %s" % (p.builddir, p.name, p.version, p.edit)))
 
 DbAction.register(ListProjectsAction)
 
@@ -175,7 +175,7 @@ class ListUsersAction(DbAction):
         users = db.list_users ()
 
         for u in users:
-            print u.name+":", u.fullname, "<"+u.email+">"
+            print(("%s: %s <%s>" % (u.name, u.fullname, u.email)))
 
 DbAction.register(ListUsersAction)
 
@@ -212,7 +212,7 @@ class DeleteProjectAction(DbAction):
 
     def execute(self, args):
         if len (args) != 1:
-            print "usage: elbe db del_project <project_dir>"
+            print("usage: elbe db del_project <project_dir>")
             return
 
         db = ElbeDB()
@@ -229,7 +229,7 @@ class SetXmlAction(DbAction):
 
     def execute(self, args):
         if len (args) != 2:
-            print "usage: elbe db set_xml <project_dir> <xml>"
+            print("usage: elbe db set_xml <project_dir> <xml>")
             return
 
         db = ElbeDB()
@@ -247,7 +247,7 @@ class BuildAction(DbAction):
 
     def execute(self, args):
         if len (args) != 1:
-            print "usage: elbe db build <project_dir>"
+            print("usage: elbe db build <project_dir>")
             return
 
         db = ElbeDB()
@@ -260,7 +260,7 @@ class BuildAction(DbAction):
         except Exception as e:
             db.update_project_files( ep )
             db.reset_busy( args[0], "build_failed" )
-            print e
+            print((str(e)))
             return
         db.reset_busy( args[0], "build_done" )
 
@@ -276,16 +276,16 @@ class GetFilesAction(DbAction):
 
     def execute(self, args):
         if len (args) != 1:
-            print "usage: elbe db get_files <project_dir>"
+            print("usage: elbe db get_files <project_dir>")
             return
 
         db = ElbeDB()
         files = db.get_project_files (args[0])
         for f in files:
             if f.description:
-                print "%-40s  %s" % (f.name, f.description)
+                print(("%-40s  %s" % (f.name, f.description)))
             else:
-                print f.name
+                print((f.name))
 
 DbAction.register(GetFilesAction)
 
@@ -306,7 +306,7 @@ class ResetProjectAction(DbAction):
         (opt, arg) = oparser.parse_args (args)
 
         if len(arg) != 1:
-            print "wrong number of arguments"
+            print("wrong number of arguments")
             oparser.print_help()
             return
 
@@ -325,7 +325,7 @@ class SetProjectVersionAction(DbAction):
 
     def execute(self, args):
         if len(args) != 2:
-            print "usage: elbe db set_project_version <project_dir> <version>"
+            print("usage: elbe db set_project_version <project_dir> <version>")
             return
 
         db = ElbeDB()
@@ -343,7 +343,7 @@ class ListVersionsAction(DbAction):
 
     def execute(self, args):
         if len(args) != 1:
-            print "usage: elbe db list_versions <project_dir>"
+            print("usage: elbe db list_versions <project_dir>")
             return
 
         db = ElbeDB()
@@ -351,9 +351,9 @@ class ListVersionsAction(DbAction):
 
         for v in versions:
             if v.description:
-                print v.version + ": " + v.description
+                print(("%s: %s" % (v.version, v.description)))
             else:
-                print v.version
+                print((v.version))
 
 DbAction.register(ListVersionsAction)
 
@@ -372,7 +372,7 @@ class SaveVersionAction(DbAction):
         (opt, arg) = oparser.parse_args (args)
 
         if len(arg) != 1:
-            print "wrong number of arguments"
+            print("wrong number of arguments")
             oparser.print_help()
             return
 
@@ -391,7 +391,7 @@ class DelVersionAction(DbAction):
 
     def execute(self, args):
         if len(args) != 2:
-            print "usage: elbe db del_version <project_dir> <version>"
+            print("usage: elbe db del_version <project_dir> <version>")
             return
 
         db = ElbeDB()
@@ -409,7 +409,7 @@ class PrintVersionXMLAction(DbAction):
 
     def execute(self, args):
         if len(args) != 2:
-            print "usage: elbe db print_version_xml <project_dir> <version>"
+            print("usage: elbe db print_version_xml <project_dir> <version>")
             return
 
         db = ElbeDB()
diff --git a/elbepack/debianize/barebox.py b/elbepack/debianize/barebox.py
index 46fdeed1..1648158b 100644
--- a/elbepack/debianize/barebox.py
+++ b/elbepack/debianize/barebox.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
diff --git a/elbepack/debianize/base.py b/elbepack/debianize/base.py
index 41349570..5f8eb36b 100644
--- a/elbepack/debianize/base.py
+++ b/elbepack/debianize/base.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
@@ -40,7 +38,7 @@ class DebianizeBase (FormMultiPage):
 
     @classmethod
     def get_debianizer (cls):
-        for t in cls.srctypes.values ():
+        for t in list(cls.srctypes.values ()):
            match = True
            for f in t.files:
                if not os.path.exists (f):
diff --git a/elbepack/debianize/debianize.py b/elbepack/debianize/debianize.py
index 2db30b0c..47a1a393 100644
--- a/elbepack/debianize/debianize.py
+++ b/elbepack/debianize/debianize.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
diff --git a/elbepack/debianize/kernel.py b/elbepack/debianize/kernel.py
index 527c47ed..186a56e5 100644
--- a/elbepack/debianize/kernel.py
+++ b/elbepack/debianize/kernel.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
diff --git a/elbepack/debianize/uboot.py b/elbepack/debianize/uboot.py
index bd188651..c2175a51 100644
--- a/elbepack/debianize/uboot.py
+++ b/elbepack/debianize/uboot.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
@@ -30,7 +28,7 @@ class UBoot (DebianizeBase):
     files = ['Kbuild', 'Kconfig', 'MAINTAINERS', 'config.mk']
 
     def __init__ (self):
-        print ("debianization of uboot is not supported at the moment")
+        print("debianization of uboot is not supported at the moment")
         sys.exit (-2)
         DebianizeBase.__init__ (self)
 
diff --git a/elbepack/debianreleases.py b/elbepack/debianreleases.py
index ee2d793f..e0506021 100644
--- a/elbepack/debianreleases.py
+++ b/elbepack/debianreleases.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 suite2codename = { 'oldoldoldstable': 'squeeze',
                    'oldoldstable': 'wheezy',
                    'oldstable': 'jessie',
@@ -32,4 +34,4 @@ suite2codename = { 'oldoldoldstable': 'squeeze',
 
 
 # generate reverse mapping
-codename2suite = dict( [(v,k) for k,v in suite2codename.items()] )
+codename2suite = dict( [(v,k) for k,v in list(suite2codename.items())] )
diff --git a/elbepack/debpkg.py b/elbepack/debpkg.py
index ba15b18f..35c3e988 100644
--- a/elbepack/debpkg.py
+++ b/elbepack/debpkg.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import string
 
@@ -51,7 +53,7 @@ def build_binary_deb( name, arch, version, description, files, deps, target_dir
     pkgdir = os.path.join( tmpdir, pkgfname )
 
     os.system( 'mkdir -p "%s"' % os.path.join( pkgdir, "DEBIAN" ) )
-    write_file( os.path.join( pkgdir, "DEBIAN" , "control" ), 0644, gen_controlfile(name, version, arch, description, deps) )
+    write_file( os.path.join( pkgdir, "DEBIAN" , "control" ), 0o644, gen_controlfile(name, version, arch, description, deps) )
 
     for (fname, instpath) in files:
         full_instpath = os.path.join( pkgdir, instpath )
diff --git a/elbepack/directories.py b/elbepack/directories.py
index 2200215c..309ce2f4 100644
--- a/elbepack/directories.py
+++ b/elbepack/directories.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import elbepack
 import os
 from pkgutil import iter_modules
diff --git a/elbepack/dosunix.py b/elbepack/dosunix.py
index a8b41833..e0b317fc 100755
--- a/elbepack/dosunix.py
+++ b/elbepack/dosunix.py
@@ -1,12 +1,30 @@
-#!/usr/bin/env python
+# ELBE - Debian Based Embedded Rootfilesystem Builder
+# Copyright (C) 2017  Linutronix GmbH
+#
+# This file is part of ELBE.
+#
+# ELBE is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# ELBE is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
-from string import split, join
+from __future__ import print_function
 
 def dos2unix_str (d):
-    return join (split (d, '\r\n'), '\n')
+    return d.replace('\r\n', '\n')
 
 def unix2dos_str (d):
-    return join (split (dos2unix_str (d), '\n'), '\r\n')
+    d = d.replace('\n', '\r\n')
+    d = d.replace('\r\r\n', '\r\n')
+    return d
 
 def __rewrite (fn, rw_func):
     with open (fn, 'r+') as f:
diff --git a/elbepack/dump.py b/elbepack/dump.py
index 45669ec1..81b39ece 100644
--- a/elbepack/dump.py
+++ b/elbepack/dump.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from elbepack.asciidoclog import ASCIIDocLog
 from datetime import datetime
 from elbepack.finetuning import do_finetuning
@@ -153,7 +155,7 @@ def check_full_pkgs(pkgs, fullpkgs, errorname, cache):
             errors += 1
 
     for cp in cache.get_installed_pkgs():
-        if not pindex.has_key(cp.name):
+        if cp.name not in pindex:
             elog.printo( "additional package %s installed, that was not requested" % cp.name )
             errors += 1
 
@@ -234,19 +236,19 @@ def elbe_report( xml, buildenv, cache, reportname, targetfs ):
     tgt_pkg_list = set()
 
     for fpath, realpath in targetfs.walk_files():
-        if index.has_key(fpath):
+        if fpath in index:
             pkg = index[fpath]
             tgt_pkg_list.add(pkg)
         else:
             pkg = "postinst generated"
 
-        if mt_index_post_fine.has_key(fpath) and mt_index.has_key(fpath):
+        if fpath in mt_index_post_fine and fpath in mt_index:
             if mt_index_post_fine[fpath] > mt_index[fpath]:
                 pkg = "modified finetuning"
-        if mt_index_post_fine.has_key(fpath):
+        if fpath in mt_index_post_fine:
             if mt_index_post_arch[fpath] > mt_index_post_fine[fpath]:
                 pkg = "from archive"
-            elif not mt_index.has_key(fpath):
+            elif fpath not in mt_index:
                 pkg = "added in finetuning"
         else:
             pkg = "added in archive"
@@ -257,9 +259,9 @@ def elbe_report( xml, buildenv, cache, reportname, targetfs ):
 
     outf.h2( "Deleted Files" )
     outf.table()
-    for fpath in mt_index.keys():
-        if not mt_index_post_arch.has_key(fpath):
-            if index.has_key(fpath):
+    for fpath in list(mt_index.keys()):
+        if fpath not in mt_index_post_arch:
+            if fpath in index:
                 pkg = index[fpath]
             else:
                 pkg = "postinst generated"
diff --git a/elbepack/efilesystem.py b/elbepack/efilesystem.py
index be7d7e25..7e6f9daa 100644
--- a/elbepack/efilesystem.py
+++ b/elbepack/efilesystem.py
@@ -15,7 +15,8 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
-#
+
+from __future__ import print_function
 
 import os
 import time
@@ -143,17 +144,17 @@ class ElbeFilesystem(Filesystem):
                 lic_text = "Error while processing license file %s: '%s'" % (os.path.join(dir, "copyright"), e.strerror)
 
             try:
-                lic_text = unicode (lic_text, encoding='utf-8')
+                lic_text = str (lic_text, encoding='utf-8')
             except:
-                lic_text = unicode (lic_text, encoding='iso-8859-1')
+                lic_text = str (lic_text, encoding='iso-8859-1')
 
 
             if not f is None:
-                f.write(unicode(os.path.basename(dir)))
-                f.write(u":\n================================================================================")
-                f.write(u"\n")
+                f.write(str(os.path.basename(dir)))
+                f.write(":\n================================================================================")
+                f.write("\n")
                 f.write(lic_text)
-                f.write(u"\n\n")
+                f.write("\n\n")
 
             if not xml_fname is None:
                 licence_xml.add_copyright_file (os.path.basename(dir), lic_text)
@@ -197,7 +198,7 @@ class ChRootFilesystem(ElbeFilesystem):
 
         self.mkdir_p ("usr/sbin")
         self.write_file ("usr/sbin/policy-rc.d",
-            0755, "#!/bin/sh\nexit 101\n")
+            0o755, "#!/bin/sh\nexit 101\n")
 
         self.mount()
         return self
diff --git a/elbepack/elbeproject.py b/elbepack/elbeproject.py
index 2232b4c1..a1034bc2 100644
--- a/elbepack/elbeproject.py
+++ b/elbepack/elbeproject.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import datetime
 import io
diff --git a/elbepack/elbexml.py b/elbepack/elbexml.py
index 7c92288a..03b407e2 100644
--- a/elbepack/elbexml.py
+++ b/elbepack/elbexml.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from elbepack.treeutils import etree
 from elbepack.validate import validate_xml
 from elbepack.xmldefaults import ElbeDefaults
@@ -25,7 +27,24 @@ from elbepack.version import elbe_version, is_devel
 from base64 import standard_b64decode
 from tempfile import NamedTemporaryFile
 
-import urllib2
+# in python3 only urllib3 is available
+try:
+    import urllib.request
+    from urllib.error import URLError
+    passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
+    authhandler = urllib.request.HTTPBasicAuthHandler(passman)
+    opener = urllib.request.build_opener(authhandler)
+    urllib.request.install_opener(opener)
+    urlopen = urllib.request.urlopen
+except ImportError:
+    import urllib2
+    from urllib2 import URLError
+    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
+    authhandler = urllib2.HTTPBasicAuthHandler(passman)
+    opener = urllib2.build_opener(authhandler)
+    urllib2.install_opener(opener)
+    urlopen = urllib2.urlopen
+
 import os
 import re
 
@@ -200,11 +219,6 @@ class ElbeXML(object):
             os.environ ["https_proxy"] = ""
             os.environ["no_proxy"] = ""
 
-        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
-        authhandler = urllib2.HTTPBasicAuthHandler(passman)
-        opener = urllib2.build_opener(authhandler)
-        urllib2.install_opener(opener)
-
         for u in urls:
             if '@' in u:
                 t = u.split('@')
@@ -218,9 +232,9 @@ class ElbeXML(object):
                 usr, passwd = auth.split(':')
                 passman.add_password(None, u, usr, passwd)
             try:
-                fp = urllib2.urlopen(u, None, 10)
+                fp = urlopen(u, None, 10)
                 fp.close()
-            except urllib2.URLError:
+            except URLError:
                 raise ValidationError (["Repository %s can not be validated" % u])
 
 
diff --git a/elbepack/filesystem.py b/elbepack/filesystem.py
index fb76756b..0d433baa 100644
--- a/elbepack/filesystem.py
+++ b/elbepack/filesystem.py
@@ -15,7 +15,8 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
-#
+
+from __future__ import print_function
 
 import os
 import shutil
@@ -98,7 +99,7 @@ class Filesystem(object):
     def listdir(self, path='', ignore=[], skiplinks=False):
         retval = [os.path.join(self.path, path, x) for x in os.listdir( self.fname(path) ) if not x in ignore]
         if skiplinks:
-            retval = filter(lambda x: (not os.path.islink(x)) and os.path.isdir(x), retval)
+            retval = [x for x in retval if (not os.path.islink(x)) and os.path.isdir(x)]
 
         return retval
 
@@ -122,7 +123,7 @@ class Filesystem(object):
         fp.close()
         return retval
 
-    def mkdir_p (self, newdir, mode=0755):
+    def mkdir_p (self, newdir, mode=0o755):
         """works the way a good mkdir -p would...
                 - already exists, silently complete
                 - regular file in the way, raise an exception
diff --git a/elbepack/finetuning.py b/elbepack/finetuning.py
index d209e1b3..2b0eabc5 100644
--- a/elbepack/finetuning.py
+++ b/elbepack/finetuning.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import gpgme
 
@@ -53,7 +55,7 @@ class RmAction(FinetuningAction):
     def execute(self, log, buildenv, target):
         files = target.glob( self.node.et.text )
 
-        if self.node.et.attrib.has_key ('exclude'):
+        if 'exclude' in self.node.et.attrib:
             exclude = self.node.et.attrib['exclude'].split (' ')
         else:
             exclude = []
@@ -340,7 +342,7 @@ class UpdatedAction(FinetuningAction):
             with open ((target.path + '/pub.key'), 'wb') as tkey:
                 tkey.write (key.getvalue ())
 
-            target.mkdir_p ("/var/cache/elbe/gnupg", mode=0700)
+            target.mkdir_p ("/var/cache/elbe/gnupg", mode=0o700)
             with target:
                 os.environ ['GNUPGHOME'] = target.path + "/var/cache/elbe/gnupg"
                 log.do ("gpg --import " + target.path + "/pub.key")
@@ -397,6 +399,6 @@ def do_finetuning(xml, log, buildenv, target):
             action = FinetuningAction( i )
             action.execute(log, buildenv, target)
         except KeyError:
-            print "Unimplemented finetuning action " + i.et.tag
+            print(("Unimplemented finetuning action '%s'" % (i.et.tag)))
         except CommandError:
             log.printo( "Finetuning Error, trying to continue anyways" )
diff --git a/elbepack/fstab.py b/elbepack/fstab.py
index d86bc23f..fc0d7415 100644
--- a/elbepack/fstab.py
+++ b/elbepack/fstab.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 
 def get_mtdnum(xml, label):
@@ -53,7 +55,7 @@ class mountpoint_dict (dict):
     def register (self, fstabentry):
         mp = fstabentry.mountpoint
 
-        if self.has_key (mp):
+        if mp in self:
             fstabentry.id = self[mp].id
         else:
             fstabentry.id = str(self.id_count)
@@ -71,7 +73,7 @@ class mountpoint_dict (dict):
             depth += 1
 
     def depthlist (self):
-        mplist = self.keys()
+        mplist = list(self.keys())
         mplist.sort (key=mountpoint_dict.mountdepth)
 
         return [self[x] for x in mplist]
diff --git a/elbepack/gpg.py b/elbepack/gpg.py
index 89b9077f..12509d95 100644
--- a/elbepack/gpg.py
+++ b/elbepack/gpg.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import gpgme
 import os
 
@@ -67,46 +67,46 @@ def check_signature(ctx, sig):
     status = OverallStatus()
 
     if sig.summary & gpgme.SIGSUM_KEY_MISSING:
-        print 'Signature with unknown key: %s' % sig.fpr
+        print(("Signature with unknown key: %s" % sig.fpr))
         status.key_missing = True
         return status
 
     # there should be a key
     key = ctx.get_key(sig.fpr)
-    print '%s <%s> (%s):' % (key.uids[0].name, key.uids[0].email, sig.fpr),
+    print(("%s <%s> (%s):" % (key.uids[0].name, key.uids[0].email, sig.fpr)))
     if sig.summary & gpgme.SIGSUM_VALID == gpgme.SIGSUM_VALID:
         # signature fully valid and trusted
-        print 'VALID (Trusted)'
+        print("VALID (Trusted)")
         return status
 
     # print detailed status in case it's not fully valid and trusted
     if sig.summary == 0:
         # Signature is valid, but the key is not ultimately trusted,
         # see: http://www.gossamer-threads.com/lists/gnupg/users/52350
-        print 'VALID (Untrusted).',
+        print("VALID (Untrusted).")
     if sig.summary & gpgme.SIGSUM_SIG_EXPIRED == gpgme.SIGSUM_SIG_EXPIRED:
-        print 'SIGNATURE EXPIRED!',
+        print("SIGNATURE EXPIRED!")
         status.sig_expired = True
     if sig.summary & gpgme.SIGSUM_KEY_EXPIRED == gpgme.SIGSUM_KEY_EXPIRED:
-        print 'KEY EXPIRED!',
+        print("KEY EXPIRED!")
         status.key_expired = True
     if sig.summary & gpgme.SIGSUM_KEY_REVOKED == gpgme.SIGSUM_KEY_REVOKED:
-        print 'KEY REVOKED!',
+        print("KEY REVOKED!")
         status.key_revoked = True
     if sig.summary & gpgme.SIGSUM_RED == gpgme.SIGSUM_RED:
-        print 'INVALID SIGNATURE!',
+        print("INVALID SIGNATURE!")
         status.invalid = True
     if sig.summary & gpgme.SIGSUM_CRL_MISSING == gpgme.SIGSUM_CRL_MISSING:
-        print 'CRL MISSING!',
+        print("CRL MISSING!")
         status.gpgme_error = True
     if sig.summary & gpgme.SIGSUM_CRL_TOO_OLD == gpgme.SIGSUM_CRL_TOO_OLD:
-        print 'CRL TOO OLD!',
+        print("CRL TOO OLD!")
         status.gpgme_error = True
     if sig.summary & gpgme.SIGSUM_BAD_POLICY == gpgme.SIGSUM_BAD_POLICY:
-        print 'UNMET POLICY REQUIREMENT!',
+        print("UNMET POLICY REQUIREMENT!")
         status.gpgme_error = True
     if sig.summary & gpgme.SIGSUM_SYS_ERROR == gpgme.SIGSUM_SYS_ERROR:
-        print 'SYSTEM ERROR!',
+        print("SYSTEM ERROR!'")
         status.gpgme_error = True
 
     return status
@@ -115,7 +115,7 @@ def check_signature(ctx, sig):
 def unsign_file(fname):
     # check for .gpg extension and create an output filename without it
     if len(fname) <= 4 or fname[len(fname)-4:] != '.gpg':
-        print 'The input file needs a .gpg extension'
+        print("The input file needs a .gpg extension")
         return None
 
     outfilename = fname[:len(fname)-4]
@@ -143,9 +143,9 @@ def unsign_file(fname):
         return outfilename
 
     except IOError as ex:
-        print ex.message
+        print((ex.message))
     except Exception as ex:
-        print 'Error checking the file %s: %s' % (fname, ex.message)
+        print(("Error checking the file %s: %s" % (fname, ex.message)))
 
     return None
 
@@ -158,7 +158,7 @@ def sign (infile, outfile, fingerprint):
     try:
         key = ctx.get_key(fingerprint)
     except gpgme.GpgmeError as ex:
-        print 'no key with fingerprint %s: %s' % (fingerprint, ex.message)
+        print(("no key with fingerprint %s: %s" % (fingerprint, ex.message)))
         pass
 
     ctx.signers = [key]
@@ -167,7 +167,7 @@ def sign (infile, outfile, fingerprint):
     try:
         ctx.sign(infile, outfile, gpgme.SIG_MODE_NORMAL)
     except Exception as ex:
-        print 'Error signing file %s' % ex.message
+        print(("Error signing file %s" % ex.message))
         pass
 
 
@@ -179,7 +179,7 @@ def sign_file(fname, fingerprint):
             with open(outfilename, 'w') as outfile:
                 sign (infile, outfile, fingerprint)
     except Exception as ex:
-        print 'Error signing file %s' % ex.message
+        print(("Error signing file %s" % ex.message))
         pass
 
 
@@ -208,6 +208,6 @@ def export_key (fingerprint, outfile):
     try:
         ctx.export(fingerprint, outfile)
     except Exception as ex:
-        print 'Error exporting key %s' % (fingerprint)
+        print(("Error exporting key %s" % (fingerprint)))
 
     return '/var/cache/elbe/gnupg/pubring.gpg'
diff --git a/elbepack/hdimg.py b/elbepack/hdimg.py
index e2834e51..aca04208 100644
--- a/elbepack/hdimg.py
+++ b/elbepack/hdimg.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 from string import digits
 
@@ -45,7 +47,7 @@ def mkfs_mtd( outf, mtd, fslabel, rfs, target ):
             continue
 
         label = v.text("label")
-        if not fslabel.has_key(label):
+        if label not in fslabel:
             continue
 
         try:
@@ -177,7 +179,7 @@ class grubinstaller_base( object ):
         self.boot = None
 
     def set_boot_entry( self, entry ):
-        print "setting boot entry"
+        print("setting boot entry")
         self.boot = entry
 
     def set_root_entry( self, entry ):
@@ -301,7 +303,7 @@ def create_partition(disk, part, ptype, fslabel, size_in_sectors, current_sector
         sz = size_to_int(part.text("size"))/sector_size
 
     g = parted.Geometry(device=disk.device, start=current_sector, length=sz)
-    if ptype != parted.PARTITION_EXTENDED and fslabel.has_key(part.text("label")) and fslabel[part.text("label")].fstype == "vfat":
+    if ptype != parted.PARTITION_EXTENDED and part.text("label") in fslabel and fslabel[part.text("label")].fstype == "vfat":
         fs = simple_fstype("fat32")
         ppart = parted.Partition(disk, ptype, fs, geometry=g)
         ppart.setFlag(_ped.PARTITION_LBA)
@@ -357,7 +359,7 @@ def create_logical_partitions(outf, disk, extended, epart, fslabel, target, grub
 
         current_sector += 2048
         lpart = create_partition(disk, logical, parted.PARTITION_LOGICAL, fslabel, size_in_sectors, current_sector)
-        if logical.has("label") and fslabel.has_key(logical.text("label")):
+        if logical.has("label") and logical.text("label") in fslabel:
             create_label(outf, disk, logical, lpart, fslabel, target, grub)
 
         current_sector += lpart.getLength();
@@ -392,7 +394,7 @@ def do_image_hd( outf, hd, fslabel, target, grub_version ):
 
         if part.tag == "partition":
             ppart = create_partition(disk, part, parted.PARTITION_NORMAL, fslabel, size_in_sectors, current_sector)
-            if fslabel.has_key(part.text("label")):
+            if part.text("label") in fslabel:
                 create_label(outf, disk, part, ppart, fslabel, target, grub)
         elif part.tag == "extended":
             ppart = create_partition(disk, part, parted.PARTITION_EXTENDED, fslabel, size_in_sectors, current_sector)
@@ -431,7 +433,7 @@ def add_binary_blob( outf, hd, target ):
         # use file from target/ dir if binary path starts with /
         if (binary.et.text[0] == '/'):
             bf = os.path.join(target, 'target', binary.et.text[1:])
-            print bf
+            print(bf)
         # else use file from /var/cache/elbe/<uuid> project dir
         else:
             bf = os.path.join(target, binary.et.text)
diff --git a/elbepack/initvmaction.py b/elbepack/initvmaction.py
index 1aa1ff57..b70414e4 100644
--- a/elbepack/initvmaction.py
+++ b/elbepack/initvmaction.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -44,7 +42,7 @@ def ensure_outdir (wdfs, opt):
     if opt.outdir is None:
         opt.outdir = "elbe-build-" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
 
-    print ("Saving generated Files to %s" % opt.outdir)
+    print("Saving generated Files to %s" % opt.outdir)
 
 def ensure_initvm_defined():
     if self.initvm == None:
@@ -61,9 +59,9 @@ class InitVMAction(object):
         cls.actiondict[action.tag] = action
     @classmethod
     def print_actions(cls):
-        print ('available subcommands are:', file=sys.stderr)
+        print("available subcommands are:", file=sys.stderr)
         for a in cls.actiondict:
-            print ('   ' + a, file=sys.stderr)
+            print("   %s" % a, file=sys.stderr)
     def __new__(cls, node):
         action = cls.actiondict[node]
         return object.__new__(action)
@@ -101,7 +99,7 @@ class StartAction(InitVMAction):
                 sys.stdout.write ("*")
                 sys.stdout.flush ()
                 time.sleep (1)
-            print ("*")
+            print("*")
 
 InitVMAction.register(StartAction)
 
@@ -177,11 +175,11 @@ class StartBuildAction(InitVMAction):
         try:
             have_session = os.system( "tmux has-session -t ElbeInitVMSession >/dev/null 2>&1" )
         except CommandError as e:
-            print ("tmux execution failed, tmux version 1.9 or higher is required")
+            print("tmux execution failed, tmux version 1.9 or higher is required")
             sys.exit(20)
         if have_session != 256:
-            print ("ElbeInitVMSession already exists in tmux.", file=sys.stderr)
-            print ("Try 'elbe initvm attach' to attach to the session.", file=sys.stderr)
+            print("ElbeInitVMSession already exists in tmux.", file=sys.stderr)
+            print("Try 'elbe initvm attach' to attach to the session.", file=sys.stderr)
             sys.exit(20)
 
         system( 'TMUX= tmux new-session -d -s ElbeInitVMSession -n initvm "cd \"%s\"; make"' % initvmdir )
@@ -216,7 +214,7 @@ class CreateAction(InitVMAction):
                 try:
                     xml = etree( exampl )
                 except ValidationError as e:
-                    print ('XML file is inavlid: ' + str(e))
+                    print("XML file is inavlid: %s" % str(e))
                 # Use default XML if no initvm was specified
                 if not xml.has( "initvm" ):
                     exampl = os.path.join (elbepack.__path__[0], "init/default-init.xml")
@@ -227,35 +225,35 @@ class CreateAction(InitVMAction):
                 os.system ('7z x -o%s "%s" source.xml' % (tmp.path, args[0]))
 
                 if not tmp.isfile ('source.xml'):
-                    print ('Iso image does not contain a source.xml file', file=sys.stderr)
-                    print ('This is not supported by "elbe initvm"', file=sys.stderr)
-                    print ('', file=sys.stderr)
-                    print ('Exiting !!!', file=sys.stderr)
+                    print("Iso image does not contain a source.xml file", file=sys.stderr)
+                    print("This is not supported by 'elbe initvm'", file=sys.stderr)
+                    print("", file=sys.stderr)
+                    print("Exiting !!!", file=sys.stderr)
                     sys.exit (20)
 
                 try:
                     exml = ElbeXML (tmp.fname ('source.xml'), url_validation=ValidationMode.NO_CHECK)
                 except ValidationError as e:
-                    print ('Iso image does contain a source.xml file.', file=sys.stderr)
-                    print ('But that xml does not validate correctly', file=sys.stderr)
-                    print ('', file=sys.stderr)
-                    print ('Exiting !!!', file=sys.stderr)
-                    print (e)
+                    print("Iso image does contain a source.xml file.", file=sys.stderr)
+                    print("But that xml does not validate correctly", file=sys.stderr)
+                    print("", file=sys.stderr)
+                    print("Exiting !!!", file=sys.stderr)
+                    print(e)
                     sys.exit (20)
 
 
-                print ('Iso Image with valid source.xml detected !')
-                print ('Image was generated using Elbe Version %s' % exml.get_elbe_version ())
+                print("Iso Image with valid source.xml detected !")
+                print("Image was generated using Elbe Version %s" % exml.get_elbe_version ())
 
                 os.system ('7z x -o%s "%s" elbe-keyring.gpg' % ('/tmp', args[0]))
 
                 if tmp.isfile ('elbe-keyring.gpg'):
-                    print ('Iso image contains a elbe-kerying')
+                    print("Iso image contains a elbe-kerying")
 
                 exampl = tmp.fname ('source.xml')
                 cdrom = args[0]
             else:
-                print ('Unknown file ending (use either xml or iso)', file=sys.stderr)
+                print("Unknown file ending (use either xml or iso)", file=sys.stderr)
                 sys.exit (20)
         else:
             # No xml File was specified, build the default elbe-init-with-ssh
@@ -276,8 +274,8 @@ class CreateAction(InitVMAction):
                 system ('%s init %s --directory "%s" "%s"' % (elbe_exe, init_opts, initvmdir, exampl))
 
         except CommandError:
-            print ("'elbe init' Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("'elbe init' Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
         # Register initvm in libvirt
@@ -303,15 +301,15 @@ class CreateAction(InitVMAction):
         try:
             system ('cd "%s"; make' % (initvmdir))
         except CommandError:
-            print ("Building the initvm Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("Building the initvm Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
         try:
             system('%s initvm start' % elbe_exe)
         except CommandError:
-            print ("Starting the initvm Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("Starting the initvm Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
         if len(args) == 1:
@@ -322,10 +320,10 @@ class CreateAction(InitVMAction):
                 try:
                     x = ElbeXML (args[0])
                 except ValidationError as e:
-                    print ('XML file is inavlid: ' + str(e))
+                    print("XML file is inavlid: %s" % str(e))
                     sys.exit(20)
                 if not x.has('project'):
-                    print ('elbe initvm ready: use "elbe initvm submit myproject.xml" to build a project');
+                    print("elbe initvm ready: use 'elbe initvm submit myproject.xml' to build a project");
                     sys.exit(0)
 
                 ret, prjdir, err = command_out_stderr ('%s control create_project' % (elbe_exe))
@@ -337,18 +335,18 @@ class CreateAction(InitVMAction):
                 ret, prjdir, err = command_out_stderr ('%s control create_project' % (elbe_exe))
 
             if ret != 0:
-                print ("elbe control create_project failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control create_project failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             prjdir = prjdir.strip()
 
             ret, msg, err = command_out_stderr ('%s control set_xml "%s %s"' % (elbe_exe, prjdir, exampl))
             if ret != 0:
-                print ("elbe control set_xml failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control set_xml failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             if opt.writeproject:
@@ -356,15 +354,15 @@ class CreateAction(InitVMAction):
                     wpf.write (prjdir)
 
             if cdrom is not None:
-                print ("Uploading CDROM. This might take a while")
+                print("Uploading CDROM. This might take a while")
                 try:
                     system ('%s control set_cdrom "%s" "%s"' % (elbe_exe, prjdir, cdrom) )
                 except CommandError:
-                    print ("elbe control set_cdrom Failed", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control set_cdrom Failed", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                     sys.exit(20)
 
-                print ("Upload finished")
+                print("Upload finished")
 
             build_opts = ''
             if opt.build_bin:
@@ -375,54 +373,54 @@ class CreateAction(InitVMAction):
             try:
                 system ('%s control build "%s" %s' % (elbe_exe, prjdir, build_opts) )
             except CommandError:
-                print ("elbe control build Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control build Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             try:
                 system ('%s control wait_busy "%s"' % (elbe_exe, prjdir) )
             except CommandError:
-                print ("elbe control wait_busy Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control wait_busy Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
-            print ("")
-            print ("Build finished !")
-            print ("")
+            print("")
+            print("Build finished !")
+            print("")
             try:
                 system ('%s control dump_file "%s" validation.txt' % (elbe_exe, prjdir) )
             except CommandError:
-                print ("Project failed to generate validation.txt", file=sys.stderr)
-                print ("Getting log.txt", file=sys.stderr)
+                print("Project failed to generate validation.txt", file=sys.stderr)
+                print("Getting log.txt", file=sys.stderr)
                 try:
                     system ('%s control dump_file "%s" log.txt' % (elbe_exe, prjdir) )
                 except CommandError:
 
-                    print ("Failed to dump log.txt", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("Failed to dump log.txt", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             if opt.skip_download:
-                print ("")
-                print ("Listing available files:")
-                print ("")
+                print("")
+                print("Listing available files:")
+                print("")
                 try:
                     system ('%s control get_files "%s"' % (elbe_exe, prjdir) )
                 except CommandError:
-                    print ("elbe control Failed", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control Failed", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                     sys.exit(20)
 
-                print ("")
-                print ('Get Files with: elbe control get_file "%s" <filename>' % prjdir)
+                print("")
+                print('Get Files with: elbe control get_file "%s" <filename>' % prjdir)
             else:
                 ensure_outdir (wdfs, opt)
 
                 try:
                     system ('%s control get_files --output "%s" "%s"' % (elbe_exe, opt.outdir, prjdir) )
                 except CommandError:
-                    print ("elbe control get_files Failed", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control get_files Failed", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                     sys.exit(20)
 
 InitVMAction.register(CreateAction)
@@ -438,8 +436,8 @@ class SubmitAction(InitVMAction):
         try:
             system ('%s initvm ensure' % elbe_exe)
         except CommandError:
-            print ("Starting the initvm Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("Starting the initvm Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
         # Init cdrom to None, if we detect it, we set it
@@ -455,50 +453,50 @@ class SubmitAction(InitVMAction):
                 tmp = TmpdirFilesystem ()
                 os.system ('7z x -o%s "%s" source.xml' % (tmp.path, args[0]))
 
-                print ('', file=sys.stderr)
+                print("", file=sys.stderr)
 
                 if not tmp.isfile ('source.xml'):
-                    print ('Iso image does not contain a source.xml file', file=sys.stderr)
-                    print ('This is not supported by "elbe initvm"', file=sys.stderr)
-                    print ('', file=sys.stderr)
-                    print ('Exiting !!!', file=sys.stderr)
+                    print("Iso image does not contain a source.xml file", file=sys.stderr)
+                    print("This is not supported by 'elbe initvm'", file=sys.stderr)
+                    print("", file=sys.stderr)
+                    print("Exiting !!!", file=sys.stderr)
                     sys.exit (20)
 
                 try:
                     exml = ElbeXML (tmp.fname ('source.xml'), url_validation=ValidationMode.NO_CHECK)
                 except ValidationError as e:
-                    print ('Iso image does contain a source.xml file.', file=sys.stderr)
-                    print ('But that xml does not validate correctly', file=sys.stderr)
-                    print ('', file=sys.stderr)
-                    print ('Exiting !!!', file=sys.stderr)
-                    print (e)
+                    print("Iso image does contain a source.xml file.", file=sys.stderr)
+                    print("But that xml does not validate correctly", file=sys.stderr)
+                    print("", file=sys.stderr)
+                    print("Exiting !!!", file=sys.stderr)
+                    print(e)
                     sys.exit (20)
 
-                print ('Iso Image with valid source.xml detected !')
-                print ('Image was generated using Elbe Version %s' % exml.get_elbe_version ())
+                print("Iso Image with valid source.xml detected !")
+                print("Image was generated using Elbe Version %s" % exml.get_elbe_version ())
 
                 xmlfile = tmp.fname ('source.xml')
                 url_validation = '--skip-urlcheck'
                 cdrom = args[0]
             else:
-                print ('Unknown file ending (use either xml or iso)', file=sys.stderr)
+                print("Unknown file ending (use either xml or iso)", file=sys.stderr)
                 sys.exit (20)
 
             outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
             cmd = '%s preprocess -o %s %s' % (elbe_exe, outxml.name, xmlfile)
             ret, msg, err = command_out_stderr (cmd)
             if ret != 0:
-                print ("elbe preprocess failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe preprocess failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
             xmlfile = outxml.name
 
             ret, prjdir, err = command_out_stderr ('%s control create_project' % (elbe_exe))
             if ret != 0:
-                print ("elbe control create_project failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control create_project failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             prjdir = prjdir.strip()
@@ -506,9 +504,9 @@ class SubmitAction(InitVMAction):
             cmd = '%s control set_xml %s %s' % (elbe_exe, prjdir, xmlfile)
             ret, msg, err = command_out_stderr (cmd)
             if ret != 0:
-                print ("elbe control set_xml failed2", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control set_xml failed2", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             if opt.writeproject:
@@ -516,15 +514,15 @@ class SubmitAction(InitVMAction):
                     wpf.write (prjdir)
 
             if cdrom is not None:
-                print ("Uploading CDROM. This might take a while")
+                print("Uploading CDROM. This might take a while")
                 try:
                     system ('%s control set_cdrom "%s" "%s"' % (elbe_exe, prjdir, cdrom) )
                 except CommandError:
-                    print ("elbe control set_cdrom Failed", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control set_cdrom Failed", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                     sys.exit(20)
 
-                print ("Upload finished")
+                print("Upload finished")
 
             build_opts = ''
             if opt.build_bin:
@@ -537,52 +535,52 @@ class SubmitAction(InitVMAction):
             try:
                 system ('%s control build "%s" %s' % (elbe_exe, prjdir, build_opts) )
             except CommandError:
-                print ("elbe control build Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control build Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
-            print ("Build started, waiting till it finishes")
+            print("Build started, waiting till it finishes")
 
             try:
                 system ('%s control wait_busy "%s"' % (elbe_exe, prjdir) )
             except CommandError:
-                print ("elbe control wait_busy Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control wait_busy Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
-            print ("")
-            print ("Build finished !")
-            print ("")
+            print("")
+            print("Build finished !")
+            print("")
             try:
                 system ('%s control dump_file "%s" validation.txt' % (elbe_exe, prjdir) )
             except CommandError:
-                print ("Project failed to generate validation.txt", file=sys.stderr)
-                print ("Getting log.txt", file=sys.stderr)
+                print("Project failed to generate validation.txt", file=sys.stderr)
+                print("Getting log.txt", file=sys.stderr)
                 try:
                     system ('%s control dump_file "%s" log.txt' % (elbe_exe, prjdir) )
                 except CommandError:
 
-                    print ("Failed to dump log.txt", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("Failed to dump log.txt", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             if opt.skip_download:
-                print ("")
-                print ("Listing available files:")
-                print ("")
+                print("")
+                print("Listing available files:")
+                print("")
                 try:
                     system ('%s control get_files "%s"' % (elbe_exe, prjdir) )
                 except CommandError:
-                    print ("elbe control get_files Failed", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control get_files Failed", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                     sys.exit(20)
 
-                print ("")
-                print ('Get Files with: elbe control get_file "%s" <filename>' % prjdir)
+                print("")
+                print('Get Files with: elbe control get_file "%s" <filename>' % prjdir)
             else:
-                print ("")
-                print ("Getting generated Files")
-                print ("")
+                print("")
+                print("Getting generated Files")
+                print("")
 
                 ensure_outdir (wdfs, opt)
 
@@ -590,8 +588,8 @@ class SubmitAction(InitVMAction):
                     system ('%s control get_files --output "%s" "%s"' % (
                             elbe_exe, opt.outdir, prjdir ))
                 except CommandError:
-                    print ("elbe control get_files Failed", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control get_files Failed", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
                     sys.exit(20)
 
                 if not opt.keep_files:
@@ -599,7 +597,7 @@ class SubmitAction(InitVMAction):
                         system ('%s control del_project "%s"' % (
                             elbe_exe, prjdir))
                     except CommandError:
-                        print ("remove project from initvm failed",
+                        print("remove project from initvm failed",
                                 file=sys.stderr)
                         sys.exit(20)
 
diff --git a/elbepack/kvm.py b/elbepack/kvm.py
index 2f2288a2..8bee0504 100644
--- a/elbepack/kvm.py
+++ b/elbepack/kvm.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import subprocess
 
@@ -32,8 +34,8 @@ def find_kvm_exe ():
             # determine kvm version
             cmd = subprocess.Popen (fname + ' --version', shell=True, stdout=subprocess.PIPE)
             for line in cmd.stdout:
-                if "version" in line:
-                    version = line.split()[3].split('(')[0].strip()
+                if "version" in str(line):
+                    version = str(line).split()[3].split('(')[0].strip()
 
             if fname == "/usr/bin/qemu-system-x86_64":
                 fname += " -enable-kvm"
diff --git a/elbepack/licencexml.py b/elbepack/licencexml.py
index a40dffcd..f60127d7 100644
--- a/elbepack/licencexml.py
+++ b/elbepack/licencexml.py
@@ -15,8 +15,8 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
-#
 
+from __future__ import print_function
 
 from elbepack.treeutils import etree
 from debian.copyright import Copyright, LicenseParagraph
@@ -28,7 +28,7 @@ import warnings
 
 warnings.simplefilter('error')
 
-remove_re = re.compile(u'[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]')
+remove_re = re.compile('[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]')
 
 def do_heuristics (fp):
     c = Copyright()
@@ -68,7 +68,7 @@ class copyright_xml (object):
         txtnode = xmlpkg.append ('text')
         txtnode.et.text = copyright
 
-        bytesio = io.StringIO (unicode(txtnode.et.text))
+        bytesio = io.StringIO (str(txtnode.et.text))
         try:
             c = Copyright (bytesio)
             files = []
diff --git a/elbepack/pbuilder.py b/elbepack/pbuilder.py
index 3ee603c3..2def890b 100644
--- a/elbepack/pbuilder.py
+++ b/elbepack/pbuilder.py
@@ -1,8 +1,31 @@
+# ELBE - Debian Based Embedded Rootfilesystem Builder
+# Copyright (C) 2017  Linutronix GmbH
+#
+# This file is part of ELBE.
+#
+# ELBE is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# ELBE is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
+
+from __future__ import print_function
+
+try:
+    import urllib.request
+    urlopen = urllib.request.urlopen
+except ImportError:
+    import urllib2
+    urlopen = urllib2.urlopen
 
 import os
-import urllib2
-
-
 
 def pbuilder_ensure_chroot (builddir):
     pass
@@ -67,7 +90,7 @@ def pbuilder_write_apt_conf (builddir, xml):
 
 def mirror_script_add_key(mirror, key_url):
     key_url = key_url.replace("LOCALMACHINE", "10.0.2.2")
-    key_conn = urllib2.urlopen(key_url, None, 10)
+    key_conn = urlopen(key_url, None, 10)
     key_text = key_conn.read()
     key_conn.close()
 
diff --git a/elbepack/pbuilderaction.py b/elbepack/pbuilderaction.py
index 0b864a9f..0c77ca3c 100644
--- a/elbepack/pbuilderaction.py
+++ b/elbepack/pbuilderaction.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -35,7 +33,7 @@ def ensure_outdir (wdfs, opt):
     if opt.outdir is None:
         opt.outdir = ".."
 
-    print ("Saving generated Files to %s" % opt.outdir)
+    print("Saving generated Files to %s" % opt.outdir)
 
 class PBuilderError(Exception):
     def __init__(self, str):
@@ -48,9 +46,9 @@ class PBuilderAction(object):
         cls.actiondict[action.tag] = action
     @classmethod
     def print_actions(cls):
-        print ('available subcommands are:', file=sys.stderr)
+        print("available subcommands are:", file=sys.stderr)
         for a in cls.actiondict:
-            print ('   ' + a, file=sys.stderr)
+            print("   %s" % a, file=sys.stderr)
     def __new__(cls, node):
         action = cls.actiondict[node]
         return object.__new__(action)
@@ -70,18 +68,18 @@ class CreateAction(PBuilderAction):
         if opt.xmlfile:
             ret, prjdir, err = command_out_stderr ('%s control create_project' % (elbe_exe))
             if ret != 0:
-                print ("elbe control create_project failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control create_project failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             prjdir = prjdir.strip()
             ret, msg, err = command_out_stderr ('%s control set_xml "%s" "%s"' % (elbe_exe, prjdir, opt.xmlfile))
 
             if ret != 0:
-                print ("elbe control set_xml failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control set_xml failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             if opt.writeproject:
@@ -92,29 +90,29 @@ class CreateAction(PBuilderAction):
         elif opt.project:
             prjdir = opt.project
         else:
-            print ('you need to specify --project option', file=sys.stderr)
+            print("you need to specify --project option", file=sys.stderr)
             sys.exit(20)
 
 
-        print ("Creating pbuilder")
+        print("Creating pbuilder")
 
         try:
             system ('%s control build_pbuilder "%s"' % (elbe_exe, prjdir))
         except CommandError:
-            print ("elbe control build_pbuilder Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("elbe control build_pbuilder Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
         try:
             system ('%s control wait_busy "%s"' % (elbe_exe, prjdir) )
         except CommandError:
-            print ("elbe control wait_busy Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("elbe control wait_busy Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
-        print ("")
-        print ("Building Pbuilder finished !")
-        print ("")
+        print("")
+        print("Building Pbuilder finished !")
+        print("")
 
 PBuilderAction.register(CreateAction)
 
@@ -128,23 +126,23 @@ class UpdateAction(PBuilderAction):
     def execute(self, opt, args):
 
         if not opt.project:
-            print ('you need to specify --project option', file=sys.stderr)
+            print("you need to specify --project option", file=sys.stderr)
             sys.exit(20)
 
         prjdir = opt.project
 
-        print ("Updating pbuilder")
+        print("Updating pbuilder")
 
         try:
             system ('%s control update_pbuilder "%s"' % (elbe_exe, prjdir))
         except CommandError:
-            print ("elbe control update_pbuilder Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("elbe control update_pbuilder Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
-        print ("")
-        print ("Updating Pbuilder finished !")
-        print ("")
+        print("")
+        print("Updating Pbuilder finished !")
+        print("")
 
 PBuilderAction.register(CreateAction)
 
@@ -162,9 +160,9 @@ class BuildAction(PBuilderAction):
         if opt.xmlfile:
             ret, prjdir, err = command_out_stderr ('%s control create_project --retries 60 "%s"' % (elbe_exe, opt.xmlfile))
             if ret != 0:
-                print ("elbe control create_project failed.", file=sys.stderr)
-                print (err, file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control create_project failed.", file=sys.stderr)
+                print(err, file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             prjdir = prjdir.strip()
@@ -172,95 +170,95 @@ class BuildAction(PBuilderAction):
             try:
                 system ('%s control build_pbuilder "%s"' % (elbe_exe, prjdir))
             except CommandError:
-                print ("elbe control build_pbuilder Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control build_pbuilder Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
             try:
                 system ('%s control wait_busy "%s"' % (elbe_exe, prjdir) )
             except CommandError:
-                print ("elbe control wait_busy Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control wait_busy Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
-            print ("")
-            print ("Building Pbuilder finished !")
-            print ("")
+            print("")
+            print("Building Pbuilder finished !")
+            print("")
         elif opt.project:
             prjdir = opt.project
             system ('%s control rm_log %s' % (elbe_exe, prjdir))
         else:
-            print ('you need to specify --project or --xmlfile option', file=sys.stderr)
+            print("you need to specify --project or --xmlfile option", file=sys.stderr)
             sys.exit(20)
 
-        print ("")
-        print ("Packing Source into tmp archive")
-        print ("")
+        print("")
+        print("Packing Source into tmp archive")
+        print("")
         try:
             system ('tar cfz "%s" .' % (tmp.fname ("pdebuild.tar.gz")))
         except CommandError:
-            print ("tar Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("tar Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
 
         for of in opt.origfile:
-            print ("")
-            print ("Pushing orig file '%s' into pbuilder" % of)
-            print ("")
+            print("")
+            print("Pushing orig file '%s' into pbuilder" % of)
+            print("")
             try:
                 system ('%s control set_orig "%s" "%s"' % (elbe_exe, prjdir, of))
             except CommandError:
-                print ("elbe control set_orig Failed", file=sys.stderr)
-                print ("Giving up", file=sys.stderr)
+                print("elbe control set_orig Failed", file=sys.stderr)
+                print("Giving up", file=sys.stderr)
                 sys.exit(20)
 
-        print ("")
-        print ("Pushing source into pbuilder")
-        print ("")
+        print("")
+        print("Pushing source into pbuilder")
+        print("")
 
         try:
             system ('%s control set_pdebuild "%s" "%s"' % (elbe_exe, prjdir, tmp.fname ("pdebuild.tar.gz")))
         except CommandError:
-            print ("elbe control set_pdebuild Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("elbe control set_pdebuild Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
         try:
             system ('%s control wait_busy "%s"' % (elbe_exe, prjdir) )
         except CommandError:
-            print ("elbe control wait_busy Failed", file=sys.stderr)
-            print ("Giving up", file=sys.stderr)
+            print("elbe control wait_busy Failed", file=sys.stderr)
+            print("Giving up", file=sys.stderr)
             sys.exit(20)
-        print ("")
-        print ("Pdebuild finished !")
-        print ("")
+        print("")
+        print("Pdebuild finished !")
+        print("")
 
         if opt.skip_download:
-            print ("")
-            print ("Listing available files:")
-            print ("")
+            print("")
+            print("Listing available files:")
+            print("")
             try:
                 system ('%s control --pbuilder-only get_files "%s"' % (elbe_exe, prjdir) )
             except CommandError:
-                print ("elbe control get_files Failed", file=sys.stderr)
-                print ("", file=sys.stderr)
-                print ("dumping logfile", file=sys.stderr)
+                print("elbe control get_files Failed", file=sys.stderr)
+                print("", file=sys.stderr)
+                print("dumping logfile", file=sys.stderr)
 
                 try:
                     system ('%s control dump_file "%s" log.txt' % (
                             elbe_exe, prjdir ))
                 except CommandError:
-                    print ("elbe control dump_file Failed", file=sys.stderr)
-                    print ("", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control dump_file Failed", file=sys.stderr)
+                    print("", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
 
                 sys.exit(20)
 
-            print ("")
-            print ('Get Files with: elbe control get_file "%s" <filename>' % prjdir)
+            print("")
+            print("Get Files with: 'elbe control get_file %s <filename>'" % prjdir)
         else:
-            print ("")
-            print ("Getting generated Files")
-            print ("")
+            print("")
+            print("Getting generated Files")
+            print("")
 
             ensure_outdir (wdfs, opt)
 
@@ -268,17 +266,17 @@ class BuildAction(PBuilderAction):
                 system ('%s control --pbuilder-only get_files --output "%s" "%s"' % (
                         elbe_exe, opt.outdir, prjdir ))
             except CommandError:
-                print ("elbe control get_files Failed", file=sys.stderr)
-                print ("", file=sys.stderr)
-                print ("dumping logfile", file=sys.stderr)
+                print("elbe control get_files Failed", file=sys.stderr)
+                print("", file=sys.stderr)
+                print("dumping logfile", file=sys.stderr)
 
                 try:
                     system ('%s control dump_file "%s" log.txt' % (
                             elbe_exe, prjdir ))
                 except CommandError:
-                    print ("elbe control dump_file Failed", file=sys.stderr)
-                    print ("", file=sys.stderr)
-                    print ("Giving up", file=sys.stderr)
+                    print("elbe control dump_file Failed", file=sys.stderr)
+                    print("", file=sys.stderr)
+                    print("Giving up", file=sys.stderr)
 
                 sys.exit(20)
 
diff --git a/elbepack/persistency.py b/elbepack/persistency.py
index ead6e5fb..0c8c6260 100644
--- a/elbepack/persistency.py
+++ b/elbepack/persistency.py
@@ -15,8 +15,8 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
-#
 
+from __future__ import print_function
 
 max_objects = 3
 
@@ -27,10 +27,10 @@ class Managed(object):
 
     @classmethod
     def register(cls, obj):
-        if len(cls.cache.keys()) >= max_objects:
+        if len(list(cls.cache.keys())) >= max_objects:
             # LRU Logic here
-            minimal = cls.cache.keys()[0]
-            for i in cls.cache.keys():
+            minimal = list(cls.cache.keys())[0]
+            for i in list(cls.cache.keys()):
                 if cls.cache[i].lastaccess < cls.cache[minimal].lastaccess:
                     minimal = i
             del cls.cache[minimal]
@@ -65,10 +65,8 @@ class Derived(Managed):
 
         Managed.__init__(self,path)
 
-        print "real init"
-        self.bla = "hello"
 
     def __del__(self):
-        print "removing object ", self.path
+        print(("removing object %s" % self.path))
 
 
diff --git a/elbepack/pkgarchive.py b/elbepack/pkgarchive.py
index b8a79ff9..2991cb26 100644
--- a/elbepack/pkgarchive.py
+++ b/elbepack/pkgarchive.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import errno
 from os import path, remove
 from shutil import rmtree, copytree, move
diff --git a/elbepack/pkgutils.py b/elbepack/pkgutils.py
index b8e82a68..88c7c8b7 100644
--- a/elbepack/pkgutils.py
+++ b/elbepack/pkgutils.py
@@ -16,13 +16,20 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
+# different module names in python 2 and 3
+try:
+    import urllib.request
+    urlopen = urllib.request.urlopen
+except ImportError:
+    import urllib2
+    urlopen = urllib2.urlopen
 
 import os
+import hashlib
 
 from tempfile import mkdtemp
-import urllib2
-import hashlib
 
 from elbepack.shellhelper import CommandError, system
 
@@ -31,10 +38,10 @@ try:
     from apt_pkg import TagFile
     virtapt_imported = True
 except ImportError:
-    print "WARNING - python-apt not available: if there are multiple versions of"
-    print " elbe-bootstrap packages on the mirror(s) elbe selects the first package it"
-    print " has found. There is no guarantee that the latest package is used."
-    print " To ensure this, the python-apt package needs to be installed."
+    print("WARNING - python-apt not available: if there are multiple versions of")
+    print(" elbe-bootstrap packages on the mirror(s) elbe selects the first package it")
+    print(" has found. There is no guarantee that the latest package is used.")
+    print(" To ensure this, the python-apt package needs to be installed.")
     virtapt_imported = False
 
 
@@ -90,11 +97,11 @@ def get_initrd_pkg( prj, defs ):
 def get_url ( arch, suite, target_pkg, mirror, comp='main' ):
     try:
         pack_url = "%s/dists/%s/%s/binary-%s/Packages" % (mirror.replace("LOCALMACHINE", "localhost"), suite, comp, arch)
-        packages = urllib2.urlopen(pack_url, None, 10)
+        packages = urlopen(pack_url, None, 10)
 
         packages = packages.readlines()
-        packages = filter( lambda x: x.startswith( "Filename" ), packages )
-        packages = filter( lambda x: x.find( target_pkg ) != -1, packages )
+        packages = [x for x in packages if x.startswith( "Filename" )]
+        packages = [x for x in packages if x.find( target_pkg ) != -1]
 
         tmp = packages.pop()
         urla = tmp.split()
@@ -165,7 +172,7 @@ def get_dsc_size( fname ):
 
     sz = os.path.getsize(fname)
     for sect in tf:
-        if sect.has_key('Files'):
+        if 'Files' in sect:
             files = sect['Files'].split('\n')
             files = [ f.strip().split(' ') for f in files ]
             for f in files:
@@ -213,10 +220,10 @@ def copy_kinitrd( prj, target_dir, defs, arch="default" ):
             if m.hexdigest() != sha1:
                 raise NoKinitrdException ('elbe-bootstrap failed to verify !!!')
         else:
-            print "-----------------------------------------------------"
-            print "WARNING:"
-            print "Using untrusted elbe-bootstrap"
-            print "-----------------------------------------------------"
+            print("-----------------------------------------------------")
+            print("WARNING:")
+            print("Using untrusted elbe-bootstrap")
+            print("-----------------------------------------------------")
 
 
         try:
diff --git a/elbepack/projectmanager.py b/elbepack/projectmanager.py
index a747de0c..a57bb4dd 100644
--- a/elbepack/projectmanager.py
+++ b/elbepack/projectmanager.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2014  Linutronix GmbH
 #
@@ -18,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 import errno
 import os
diff --git a/elbepack/repomanager.py b/elbepack/repomanager.py
index ffeba76d..bd233fa6 100644
--- a/elbepack/repomanager.py
+++ b/elbepack/repomanager.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import shutil
 
diff --git a/elbepack/rfs.py b/elbepack/rfs.py
index 1a72dc81..a612cb4c 100644
--- a/elbepack/rfs.py
+++ b/elbepack/rfs.py
@@ -16,9 +16,20 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
+try:
+    import urllib.parse
+    import urllib.request
+    urlopen = urllib.request.urlopen
+    urlsplit = urllib.parse.urlsplit
+except ImportError:
+    import urlparse
+    import urllib2
+    urlopen = urllib2.urlopen
+    urlsplit = urlparse.urlsplit
+
 import os
-import urlparse
-import urllib2
 
 from elbepack.efilesystem import BuildImgFs
 from elbepack.templates import write_pack_template, get_preseed, preseed_to_text
@@ -44,13 +55,12 @@ class BuildEnv ():
         if not self.rfs.isfile( "etc/elbe_version" ):
             # avoid starting daemons inside the buildenv
             self.rfs.mkdir_p ("usr/sbin")
-            self.rfs.write_file ("usr/sbin/policy-rc.d",
-                0755, "#!/bin/sh\nexit 101\n")
+            self.rfs.write_file ("usr/sbin/policy-rc.d", 0o755, "#!/bin/sh\nexit 101\n")
             self.debootstrap ()
             self.fresh_debootstrap = True
             self.need_dumpdebootstrap = True
         else:
-            print 'work on existing rfs'
+            print("work on existing rfs")
             self.fresh_debootstrap = False
             self.need_dumpdebootstrap = False
 
@@ -198,7 +208,7 @@ class BuildEnv ():
                     l = url.text('key').strip()    # URL to key
                     name = l.split('/')[-1]        # Filename of key
 
-                    myKey = urllib2.urlopen(l).read()
+                    myKey = urlopen(l).read()
                     self.log.do('echo "%s" > %s' % (myKey, self.rfs.fname("tmp/key.pub")))
                     with self.rfs:
                         self.log.chroot(self.rfs.path, 'apt-key add /tmp/key.pub' )
@@ -210,13 +220,13 @@ class BuildEnv ():
         if self.rfs.exists("etc/apt/sources.list"):
             self.rfs.remove("etc/apt/sources.list")
 
-        self.rfs.write_file ("etc/apt/sources.list", 0644, mirror)
+        self.rfs.write_file ("etc/apt/sources.list", 0o644, mirror)
 
         self.rfs.mkdir_p( "var/cache/elbe" )
 
         preseed = get_preseed( self.xml )
         preseed_txt = preseed_to_text( preseed )
-        self.rfs.write_file( "var/cache/elbe/preseed.txt", 0644, preseed_txt )
+        self.rfs.write_file( "var/cache/elbe/preseed.txt", 0o644, preseed_txt )
         with self.rfs:
             self.log.chroot( self.rfs.path, 'debconf-set-selections < %s' % self.rfs.fname("var/cache/elbe/preseed.txt") )
 
@@ -240,7 +250,7 @@ class BuildEnv ():
                 if not 'pin' in repo.et.attrib:
                     continue
 
-                origin = urlparse.urlsplit(repo.et.text.strip()).hostname
+                origin = urlsplit(repo.et.text.strip()).hostname
                 pin = repo.et.attrib['pin']
                 if 'package' in repo.et.attrib:
                     package = repo.et.attrib['package']
diff --git a/elbepack/rpcaptcache.py b/elbepack/rpcaptcache.py
index a5be48fb..8c882f76 100644
--- a/elbepack/rpcaptcache.py
+++ b/elbepack/rpcaptcache.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from multiprocessing.util import Finalize
 from apt_pkg import config, version_compare
 from apt import Cache
diff --git a/elbepack/shellhelper.py b/elbepack/shellhelper.py
index 298cb7d6..c88c77b2 100644
--- a/elbepack/shellhelper.py
+++ b/elbepack/shellhelper.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 from subprocess import Popen, PIPE, STDOUT
 
diff --git a/elbepack/soapclient.py b/elbepack/soapclient.py
index 50261faa..157ac3fc 100644
--- a/elbepack/soapclient.py
+++ b/elbepack/soapclient.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013  Linutronix GmbH
 #
@@ -20,18 +18,27 @@
 
 from __future__ import print_function
 
+# different module names in python2 and 3
+try:
+    from urllib.error import URLError
+except ImportError:
+    from urllib2 import URLError
+
+try:
+    from http.client import BadStatusLine
+except ImportError:
+    from httplib import BadStatusLine
+
 import binascii
-from suds.client import Client
-from urllib2 import URLError
-from httplib import BadStatusLine
 import socket
 import time
 import sys
 import os
 import fnmatch
+import deb822                     # package for dealing with Debian related data
 
+from suds.client import Client
 from datetime import datetime
-import deb822                     # package for dealing with Debian related data
 
 from elbepack.filesystem import Filesystem
 from elbepack.elbexml import ElbeXML, ValidationMode
@@ -98,11 +105,11 @@ class ElbeSoapClient(object):
                 retry = retry - 1
                 if not retry:
                     fp.close ()
-                    print ("file transfer failed", file=sys.stderr)
+                    print("file transfer failed", file=sys.stderr)
                     sys.exit(20)
 
             if ret == "FileNotFound":
-                print (ret, file=sys.stderr)
+                print(ret, file=sys.stderr)
                 sys.exit(20)
             if ret == "EndOfFile":
                 fp.close ()
@@ -118,9 +125,9 @@ class ClientAction(object):
         cls.actiondict[action.tag] = action
     @classmethod
     def print_actions(cls):
-        print ('available subcommands are:', file=sys.stderr)
+        print("available subcommands are:", file=sys.stderr)
         for a in cls.actiondict:
-            print ('   ' + a, file=sys.stderr)
+            print("   %s" % a, file=sys.stderr)
     def __new__(cls, node):
         action = cls.actiondict[node]
         return object.__new__(action)
@@ -136,7 +143,7 @@ class RemoveLogAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control rm_log <project_dir>", file=sys.stderr)
+            print("usage: elbe control rm_log <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -157,9 +164,9 @@ class ListProjectsAction(ClientAction):
 
         try:
             for p in projects.SoapProject:
-                print (p.builddir + '\t' + p.name + '\t' + p.version + '\t' + p.status + '\t' + str(p.edit))
+                print("%s\t%s\t%s\t%s\t%s" %  (p.builddir, p.name, p.version, p.status, str(p.edit)))
         except AttributeError:
-            print ('No projects configured in initvm')
+            print("No projects configured in initvm")
 
 ClientAction.register(ListProjectsAction)
 
@@ -174,7 +181,7 @@ class ListUsersAction(ClientAction):
         users = client.service.list_users ()
 
         for u in users.string:
-            print (u)
+            print(u)
 
 ClientAction.register(ListUsersAction)
 
@@ -188,7 +195,7 @@ class CreateProjectAction(ClientAction):
     def execute(self, client, opt, args):
 
         uuid = client.service.new_project ()
-        print (uuid)
+        print(uuid)
 
 ClientAction.register(CreateProjectAction)
 
@@ -201,7 +208,7 @@ class ResetProjectAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control reset_project <project_dir>", file=sys.stderr)
+            print("usage: elbe control reset_project <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -219,7 +226,7 @@ class DeleteProjectAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control del_project <project_dir>", file=sys.stderr)
+            print("usage: elbe control del_project <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -236,7 +243,7 @@ class SetXmlAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 2:
-            print ("usage: elbe control set_xml <project_dir> <xml>", file=sys.stderr)
+            print("usage: elbe control set_xml <project_dir> <xml>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -245,17 +252,17 @@ class SetXmlAction(ClientAction):
         try:
             x = ElbeXML (filename, skip_validate=True, url_validation=ValidationMode.NO_CHECK)
         except IOError as e:
-            print ("%s is not a valid elbe xml file" % filename)
+            print("%s is not a valid elbe xml file" % filename)
             sys.exit (20)
 
         if not x.has ('target'):
-          print ("<target> is missing, this file can't be built in an initvm",
+          print("<target> is missing, this file can't be built in an initvm",
                   file=sys.stderr)
           sys.exit (20)
 
         size = 1024 * 1024
         part = 0
-        with open (filename, "r") as fp:
+        with open (filename, "rb") as fp:
             while (True):
                 xml_base64 = binascii.b2a_base64(fp.read (size))
                 # finish upload
@@ -270,10 +277,10 @@ class SetXmlAction(ClientAction):
                                                        xml_base64,
                                                        part)
                 if part == -1:
-                    print ("project busy, upload not allowed")
+                    print("project busy, upload not allowed")
                     return part
                 if part == -2:
-                    print ("upload of xml finished")
+                    print("upload of xml finished")
                     return 0
 
 
@@ -289,7 +296,7 @@ class BuildAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control build <project_dir>", file=sys.stderr)
+            print("usage: elbe control build <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -308,7 +315,7 @@ class BuildSysrootAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control build-sysroot <project_dir>", file=sys.stderr)
+            print("usage: elbe control build-sysroot <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -326,7 +333,7 @@ class GetFileAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 2:
-            print ("usage: elbe control get_file <project_dir> <file>", file=sys.stderr)
+            print("usage: elbe control get_file <project_dir> <file>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -353,7 +360,7 @@ class BuildChrootAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control build_chroot_tarball <project_dir>", file=sys.stderr)
+            print("usage: elbe control build_chroot_tarball <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -371,7 +378,7 @@ class DumpFileAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 2:
-            print ("usage: elbe control dump_file <project_dir> <file>", file=sys.stderr)
+            print("usage: elbe control dump_file <project_dir> <file>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -381,7 +388,7 @@ class DumpFileAction(ClientAction):
         while True:
             ret = client.service.get_file (builddir, filename, part)
             if ret == "FileNotFound":
-                print (ret, file=sys.stderr)
+                print(ret, file=sys.stderr)
                 sys.exit(20)
             if ret == "EndOfFile":
                 return
@@ -400,7 +407,7 @@ class GetFilesAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control get_files <project_dir>", file=sys.stderr)
+            print("usage: elbe control get_files <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -417,9 +424,9 @@ class GetFilesAction(ClientAction):
 
             nfiles += 1
             try:
-                print ("%s \t(%s)" % (f.name, f.description))
+                print("%s \t(%s)" % (f.name, f.description))
             except AttributeError:
-                print ("%s" % (f.name))
+                print("%s" % (f.name))
 
             if opt.output:
                 fs = Filesystem ('/')
@@ -442,7 +449,7 @@ class WaitProjectBusyAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control wait_busy <project_dir>", file=sys.stderr)
+            print("usage: elbe control wait_busy <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -464,13 +471,13 @@ class WaitProjectBusyAction(ClientAction):
 
                         localtime = time.asctime(time.localtime(time.time()))
                         try:
-                            print (localtime + " -- " + log[1].replace('\n', ''))
+                            print(localtime + " -- " + log[1].replace('\n', ''))
                         except IndexError:
                             pass
                     else:
                         time.sleep(1)
                 else:
-                    print ("strange part: %d (skipped)" % part)
+                    print("strange part: %d (skipped)" % part)
                     part = part+1
 
 ClientAction.register(WaitProjectBusyAction)
@@ -486,7 +493,7 @@ class SetCdromAction(ClientAction):
         size = 1024 * 1024
 
         if len (args) != 2:
-            print ("usage: elbe control set_cdrom <project_dir> <cdrom file>", file=sys.stderr)
+            print("usage: elbe control set_cdrom <project_dir> <cdrom file>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -515,7 +522,7 @@ class SetOrigAction(ClientAction):
         size =  1024 * 1024
 
         if len (args) != 2:
-            print ("usage: elbe control set_orig <project_dir> <orig file>", file=sys.stderr)
+            print("usage: elbe control set_orig <project_dir> <orig file>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -542,7 +549,7 @@ class ShutdownInitvmAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 0:
-            print ("usage: elbe control shutdown_initvm", file=sys.stderr)
+            print("usage: elbe control shutdown_initvm", file=sys.stderr)
             sys.exit(20)
 
         # if shutdown kills the daemon before it can answer the request
@@ -564,7 +571,7 @@ class SetPdebuilderAction(ClientAction):
         size = 1024 * 1024
 
         if len (args) != 2:
-            print ("usage: elbe control set_pdebuild <project_dir> <pdebuild file>", file=sys.stderr)
+            print("usage: elbe control set_pdebuild <project_dir> <pdebuild file>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -591,7 +598,7 @@ class BuildPbuilderAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control build_pbuilder <project_dir>", file=sys.stderr)
+            print("usage: elbe control build_pbuilder <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -608,7 +615,7 @@ class UpdatePbuilderAction(ClientAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe control update_pbuilder <project_dir>", file=sys.stderr)
+            print("usage: elbe control update_pbuilder <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -623,9 +630,9 @@ class RepoAction(ClientAction):
         cls.repoactiondict[action.tag] = action
     @classmethod
     def print_actions(cls):
-        print ('available subcommands are:', file=sys.stderr)
+        print("available subcommands are:", file=sys.stderr)
         for a in cls.repoactiondict:
-            print ('   ' + a, file=sys.stderr)
+            print("   %s" % a, file=sys.stderr)
     def __new__(cls, node):
         action = cls.repoactiondict[node]
         return object.__new__(action)
@@ -640,7 +647,7 @@ class ListPackagesAction(RepoAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe prjrepo list_packages <project_dir>", file=sys.stderr)
+            print("usage: elbe prjrepo list_packages <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -658,7 +665,7 @@ class DownloadAction(RepoAction):
 
     def execute(self, client, opt, args):
         if len (args) != 1:
-            print ("usage: elbe prjrepo download <project_dir>", file=sys.stderr)
+            print("usage: elbe prjrepo download <project_dir>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -670,7 +677,6 @@ class DownloadAction(RepoAction):
         client.download_file (builddir, filename, dst_fname)
         print("%s saved" % dst_fname)
 
-
 RepoAction.register(DownloadAction)
 
 
@@ -685,7 +691,7 @@ class UploadPackageAction(RepoAction):
         # Uploads file f into builddir in intivm
         size = 1024 * 1024
         part = 0
-        with open (f, "r") as fp:
+        with open (f, "rb") as fp:
             while (True):
                 xml_base64 = binascii.b2a_base64(fp.read (size))
                 # finish upload
@@ -700,15 +706,15 @@ class UploadPackageAction(RepoAction):
                                                        xml_base64,
                                                        part)
                 if part == -1:
-                    print ("project busy, upload not allowed")
+                    print("project busy, upload not allowed")
                     return -1
                 if part == -2:
-                    print ("Upload of package finished.")
+                    print("Upload of package finished.")
                     break
 
     def execute(self, client, opt, args):
         if len (args) != 2:
-            print ("usage: elbe prjrepo upload_pkg <project_dir> <deb/dsc file>", file=sys.stderr)
+            print("usage: elbe prjrepo upload_pkg <project_dir> <deb/dsc file>", file=sys.stderr)
             sys.exit(20)
 
         builddir = args[0]
@@ -721,7 +727,7 @@ class UploadPackageAction(RepoAction):
 
         # Check filetype
         if filename[-3:] not in ['dsc','deb']:
-            print ("Error: Only .dsc and .deb files allowed to upload.")
+            print("Error: Only .dsc and .deb files allowed to upload.")
         else:
             filetype = filename[-4:]
 
@@ -741,12 +747,12 @@ class UploadPackageAction(RepoAction):
         # Abort if one or more source files are missing
         if abort: sys.exit(20)
 
-        print ("Start uploading file(s)...")
+        print("Start uploading file(s)...")
         for f in files:
             print("Upload %s..." % f)
             self.upload_file(client, f, builddir)
 
-        print ("Including Package in initvm...")
+        print("Including Package in initvm...")
         client.service.include_package(builddir, filename)
 
 
diff --git a/elbepack/templates.py b/elbepack/templates.py
index 9808ad1c..82e46994 100644
--- a/elbepack/templates.py
+++ b/elbepack/templates.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 
 from elbepack.treeutils import etree
@@ -34,11 +36,11 @@ def template(fname, d, linebreak=False):
         else:
             return Template(filename=fname).render(**d)
     except:
-        print exceptions.text_error_template().render()
+        print((exceptions.text_error_template().render()))
         raise
 
 def write_template( outname, fname, d, linebreak=False ):
-    outfile = file(outname, "w")
+    outfile = open(outname, "w")
     outfile.write( template( fname, d, linebreak ) )
     outfile.close()
 
@@ -92,7 +94,7 @@ def get_initvm_preseed( xml ):
 
 def preseed_to_text( pres ):
     retval = ""
-    for k,v in pres.items():
+    for k,v in list(pres.items()):
         retval += "%s\t%s\t%s\t%s\n" % (k[0], k[1], v[0], v[1])
 
     return retval
diff --git a/elbepack/toolchain.py b/elbepack/toolchain.py
index b1b7deb1..72906bc0 100644
--- a/elbepack/toolchain.py
+++ b/elbepack/toolchain.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import string
 import glob
 import os
diff --git a/elbepack/treeutils.py b/elbepack/treeutils.py
index 64b04a05..cd45a4db 100644
--- a/elbepack/treeutils.py
+++ b/elbepack/treeutils.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from lxml.etree import ElementTree, SubElement, Element
 from lxml.etree import XMLParser,parse
 import copy
@@ -29,9 +31,9 @@ class eiter(object):
     def __iter__(self):
         return self
 
-    def next(self):
+    def __next__(self):
         while True:
-            n = self.it.next()
+            n = next(self.it)
             # A Comment has a callable tag
             # A better way for this predicate would be nice
             if not callable(n.tag):
@@ -45,9 +47,9 @@ class ebase(object):
 
     def text( self, path, **args ):
         el = self.et.find("./"+path)
-        if (el is None) and not args.has_key("default"):
+        if (el is None) and "default" not in args:
             raise Exception( "Cant find path %s" % path )
-        elif (el is None) and args.has_key("default"):
+        elif (el is None) and "default" in args:
             default = args["default"]
             if type(default) == str:
                 return default
@@ -68,7 +70,7 @@ class ebase(object):
             return None
 
     def all( self, path ):
-        return map(elem, self.et.findall(path))
+        return list(map(elem, self.et.findall(path)))
 
     def __iter__( self ):
         return eiter(iter(self.et))
diff --git a/elbepack/updated.py b/elbepack/updated.py
index 3364c593..41ddf3c0 100644
--- a/elbepack/updated.py
+++ b/elbepack/updated.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2015 emtrion GmbH
 # Copyright (C) 2014  Linutronix GmbH
@@ -19,6 +17,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import apt
 import apt_pkg
 import errno
@@ -92,15 +92,15 @@ class UpdateStatus:
             try:
                 self.monitor.service.msg (msg)
             except:
-                print "logging to monitor failed, removing monitor connection"
+                print("logging to monitor failed, removing monitor connection")
                 self.monitor = None
-                print msg
+                print(msg)
         try:
             syslog (msg)
         except:
-            print msg
+            print(msg)
         if self.verbose:
-            print msg
+            print(msg)
 
 class UpdateApplication (Application):
     def __init__(self, *args, **kargs):
@@ -133,8 +133,8 @@ class UpdateService (ServiceBase):
 
         try:
             apply_update (fname, self.app.status)
-        except Exception, err:
-            print Exception, err
+        except Exception as err:
+            print(("%s" % str(err)))
             self.app.status.set_finished ('error')
             return "apply snapshot %s failed" % version
 
@@ -505,7 +505,7 @@ def action_select (upd_file, status):
     if os.path.isdir (prefix + "repo"):
         try:
             update_sourceslist (xml, prefix + "repo", status)
-        except Exception, err:
+        except Exception as err:
             status.log (str (err))
             status.set_finished ('error')
             status.log ("update apt sources list failed: " + prefix)
@@ -513,7 +513,7 @@ def action_select (upd_file, status):
 
         try:
             apply_update ("/tmp/new.xml", status)
-        except Exception, err:
+        except Exception as err:
             status.log (str (err))
             status.set_finished ('error')
             status.log ("apply update failed: " + prefix)
diff --git a/elbepack/updated_monitors.py b/elbepack/updated_monitors.py
index 4fc80761..d2a8aa4e 100644
--- a/elbepack/updated_monitors.py
+++ b/elbepack/updated_monitors.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2015 emtrion GmbH
 # Copyright (C) 2014  Linutronix GmbH
@@ -19,6 +17,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 import threading
 import pyinotify
diff --git a/elbepack/updatepkg.py b/elbepack/updatepkg.py
index 405a6538..597bcf69 100644
--- a/elbepack/updatepkg.py
+++ b/elbepack/updatepkg.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2013, 2014  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import os
 
 from shutil import rmtree, copyfile, copytree
@@ -78,7 +78,7 @@ def gen_update_pkg (project, xml_filename, upd_filename,
             xmlindex[name] = p
 
             if not name in instindex:
-                print "package removed: " + name
+                print(("package removed: %s" % name))
                 continue
 
             ipkg = instindex[name]
@@ -87,22 +87,22 @@ def gen_update_pkg (project, xml_filename, upd_filename,
             pfname = ipkg.installed_deb
 
             if comp == 0:
-                print "package ok: " + name + "-" + ipkg.installed_version
+                print(("package ok: %s-%s" % (name, ipkg.installed_version)))
                 if debug:
                     fnamelist.append( pfname )
                 continue
 
             if comp > 0:
-                print "package upgrade: " + pfname
+                print(("package upgrade: %s" % pfname))
                 fnamelist.append( pfname )
             else:
-                print "package downgrade: " + name + "-" + ipkg.installed_version
+                print(("package downgrade: %s-%s" % (name, ipkg.installed_version)))
 
         for p in instpkgs:
             if p.name in xmlindex:
                 continue
 
-            print "package new installed " + p.name
+            print(("package %s newly installed" % p.name))
             pfname = p.installed_deb
             fnamelist.append( pfname )
 
@@ -134,14 +134,14 @@ def gen_update_pkg (project, xml_filename, upd_filename,
 
     if project.presh_file:
         copyfile (project.presh_file, update + '/pre.sh')
-        os.chmod (update + '/pre.sh', 0755)
+        os.chmod (update + '/pre.sh', 0o755)
 
     if project.postsh_file:
         copyfile (project.postsh_file, update + '/post.sh')
-        os.chmod (update + '/post.sh', 0755)
+        os.chmod (update + '/post.sh', 0o755)
 
     if cmd_dir:
-        inlucdedir (update, 'cmd', cmd_dir, mode=0755)
+        inlucdedir (update, 'cmd', cmd_dir, mode=0o755)
 
     if cfg_dir:
         inlucdedir (update, 'conf', cfg_dir)
diff --git a/elbepack/validate.py b/elbepack/validate.py
index 2e0a59a5..b9260c5b 100644
--- a/elbepack/validate.py
+++ b/elbepack/validate.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 from lxml import etree
 from lxml.etree import XMLParser,parse
diff --git a/elbepack/version.py b/elbepack/version.py
index 8eb85552..d4c83e6b 100644
--- a/elbepack/version.py
+++ b/elbepack/version.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
 # ELBE - Debian Based Embedded Rootfilesystem Builder
 # Copyright (C) 2016  Linutronix GmbH
 #
@@ -18,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 from elbepack.directories import pack_dir
 from platform import linux_distribution
 
diff --git a/elbepack/virtapt.py b/elbepack/virtapt.py
index 2c2354be..9337a048 100644
--- a/elbepack/virtapt.py
+++ b/elbepack/virtapt.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import apt_pkg
 import os
 import sys
@@ -27,7 +29,6 @@ from tempfile import mkdtemp
 from elbepack.shellhelper import system
 from elbepack.directories import elbe_pubkey_fname
 
-
 class VirtApt:
     def __init__ (self, name, arch, suite, sources, prefs, keylist=[]):
 
@@ -82,10 +83,9 @@ class VirtApt:
         pass
 
     def pulse (self, obj):
-        #print "updating in progress", obj
         return True
 
-    def mkdir_p (self, newdir, mode=0755):
+    def mkdir_p (self, newdir, mode=0o755):
         """works the way a good mkdir -p would...
                 - already exists, silently complete
                 - regular file in the way, raise an exception
@@ -120,8 +120,8 @@ class VirtApt:
     def setup_gpg (self):
         ring_path = self.projectpath + "/etc/apt/trusted.gpg"
         if not os.path.isdir ("/etc/apt/trusted.gpg.d"):
-            print ("/etc/apt/trusted.gpg.d doesn't exist")
-            print ("apt-get install debian-archive-keyring may fix this problem")
+            print("/etc/apt/trusted.gpg.d doesn't exist")
+            print("apt-get install debian-archive-keyring may fix this problem")
             sys.exit (20)
 
         system ('cp /etc/apt/trusted.gpg "%s"' % ring_path )
@@ -136,13 +136,13 @@ class VirtApt:
 
         trustkeys = os.listdir("/etc/apt/trusted.gpg.d")
         for key in trustkeys:
-            print "Import %s: " % key
+            print(("Import %s: " % key))
             try:
                 system ('gpg %s --import "%s"' % (
                     gpg_options,
                     os.path.join ("/etc/apt/trusted.gpg.d", key)))
             except CommandError as e:
-                print "adding elbe-pubkey to keyring failed"
+                print("adding elbe-pubkey to keyring failed")
 
     def add_pubkey_url (self, url):
         ring_path = self.projectpath + "/etc/apt/trusted.gpg"
diff --git a/elbepack/xmldefaults.py b/elbepack/xmldefaults.py
index 147d4be6..520e7cc0 100644
--- a/elbepack/xmldefaults.py
+++ b/elbepack/xmldefaults.py
@@ -1,3 +1,22 @@
+# ELBE - Debian Based Embedded Rootfilesystem Builder
+# Copyright (C) 2017  Linutronix GmbH
+#
+# This file is part of ELBE.
+#
+# ELBE is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# ELBE is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
+
+from __future__ import print_function
 
 import random
 import string
@@ -176,7 +195,7 @@ def get_random_mac():
     binaddr = [random.randint(0,255) for i in range(6) ]
     binaddr[0] &= 0xfe
     binaddr[0] |= 0x02
-    s = map( lambda x: "%02x" % x, binaddr )
+    s = ["%02x" % x for x in binaddr]
 
     return str(":").join (s)
 
@@ -185,10 +204,10 @@ class ElbeDefaults(object):
 
     def __init__(self, build_type):
 
-        if not defaults.has_key(build_type):
-            print "Please specify a valid buildtype."
-            print "Valid buildtypes:"
-            print defaults.keys()
+        if build_type not in defaults:
+            print("Please specify a valid buildtype.")
+            print("Valid buildtypes:")
+            print((list(defaults.keys())))
             sys.exit(20)
 
         self.defaults = defaults[build_type]
@@ -197,9 +216,9 @@ class ElbeDefaults(object):
         self.generic_defaults = archindep_defaults
 
     def __getitem__( self, key ):
-        if self.defaults.has_key( key ):
+        if key in self.defaults:
             return self.defaults[key]
-        if self.generic_defaults.has_key( key ):
+        if key in self.generic_defaults:
             return self.generic_defaults[key]
 
         return None
diff --git a/elbepack/xmlpreprocess.py b/elbepack/xmlpreprocess.py
index 050d3e1b..9c251bb9 100644
--- a/elbepack/xmlpreprocess.py
+++ b/elbepack/xmlpreprocess.py
@@ -16,6 +16,8 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 import sys
 from lxml import etree
 from lxml.etree import XMLParser,parse
diff --git a/elbepack/xsdtoasciidoc.mako b/elbepack/xsdtoasciidoc.mako
index 68def262..861272f4 100644
--- a/elbepack/xsdtoasciidoc.mako
+++ b/elbepack/xsdtoasciidoc.mako
@@ -12,7 +12,7 @@ MINI = "{http://www.w3.org/2001/XMLSchema}minInclusive"
 
 def docindent( s, indent=0 ):
   lines = s.splitlines()
-  lines = map(string.strip, lines)
+  lines = map(str('').strip, lines)
   lines = map(lambda x: indent*" "+x, lines)
   return str('').join(lines).strip()
 
diff --git a/elbepack/ziparchives.py b/elbepack/ziparchives.py
index af5ee931..094af940 100644
--- a/elbepack/ziparchives.py
+++ b/elbepack/ziparchives.py
@@ -16,6 +16,7 @@
 # You should have received a copy of the GNU General Public License
 # along with ELBE.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 
 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
 import os
@@ -35,7 +36,7 @@ def create_zip_archive( zipfilename, path, inarchpath ):
                     archname = archname[2:]
                 zi = ZipInfo( archname)
                 stat = os.stat( path + '/' + archname )
-                zi.external_attr = stat.st_mode << 16L
+                zi.external_attr = stat.st_mode << 16
                 # this hack is needed to use the external attributes
                 # there is no way to set a zipinfo object directly to an archive
                 with open (filename, 'rb') as f:
diff --git a/setup.py b/setup.py
index 63bf330f..2f42c9a3 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 import subprocess
 import os
@@ -35,7 +35,7 @@ class my_install(install):
                                   stdout=subprocess.PIPE,
                                   cwd=docs_dir,
                                   env=envvars).communicate()[0]
-        print output
+        print(output)
 
 setup(name='elbe',
       version=elbe_version,
diff --git a/test/modify_rfs.py b/test/modify_rfs.py
index a1934863..1a7af63a 100644
--- a/test/modify_rfs.py
+++ b/test/modify_rfs.py
@@ -10,7 +10,7 @@ class AsyncStatus:
     def __init__ (self):
         pass
     def status (self, msg):
-        print "current status: " + msg
+        print("current status: " + msg)
 
 xml = elbexml.ElbeXML('source.xml')
 log = asciidoclog.ASCIIDocLog( "update.log" )
@@ -22,11 +22,11 @@ from elbepack.rpcaptcache import get_rpcaptcache
 # Use "with br" to mount the necessary bind mounts
 with br:
     cc = get_rpcaptcache(br.rfs, "aptcache.log", "armel", notifier=status)
-    print "SECTIONS: ", cc.get_sections()
+    print("SECTIONS: ", cc.get_sections())
     time.sleep (2)
-    print "SHELLS: ", cc.get_pkglist('shells')
+    print("SHELLS: ", cc.get_pkglist('shells'))
     time.sleep (2)
-    print "QUICKPLOT: ", cc.get_dependencies('quickplot')
+    print("QUICKPLOT: ", cc.get_dependencies('quickplot'))
     time.sleep (2)
     cc.mark_install('quickplot','2')
     cc.commit()
diff --git a/test/updated.py b/test/updated.py
index 10729669..3c04ef03 100755
--- a/test/updated.py
+++ b/test/updated.py
@@ -16,7 +16,7 @@ from wsgiref.simple_server import make_server
 class MonitorService (ServiceBase):
     @rpc (String)
     def msg (self, m):
-        print m
+        print(m)
 
 class MonitorThread (threading.Thread):
     def __init__ (self, port):
@@ -25,7 +25,7 @@ class MonitorThread (threading.Thread):
         self.server = None
 
     def run (self):
-        print "monitor ready :%s" % (self.port)
+        print("monitor ready :%s" % (self.port))
         application = Application([MonitorService], 'monitor',
                                   in_protocol=Soap11(validator='lxml'),
                                   out_protocol=Soap11())
@@ -89,7 +89,7 @@ wsdl = "http://" + target + ":" + port + "/?wsdl"
 try:
     control = Client (wsdl)
 except:
-    print wsdl, "not reachable"
+    print(wsdl, "not reachable")
     sys.exit (1)
 
 monitor = MonitorThread (monitorport)
@@ -101,7 +101,7 @@ try:
     monitor_wsdl = "http://" + host + ":" + monitorport + "/?wsdl"
     control.service.register_monitor (monitor_wsdl)
 except:
-    print "monitor couldn't be registered (port already in use?)"
+    print("monitor couldn't be registered (port already in use?)")
     shutdown (monitor)
 
 while 1:
@@ -110,20 +110,20 @@ while 1:
     try:
         snapshots = s.split (',')
 
-        print "select snapshot:"
+        print("select snapshot:")
         i = 0
         for s in snapshots:
             if s:
-                print "  [%d] %s" % (i, s)
+                print("  [%d] %s" % (i, s))
             i = i + 1
     except:
-        print "no snapshots available"
+        print("no snapshots available")
 
     sys.stdout.write ("% ")
     sys.stdout.flush ()
 
     try:
-        n = int (raw_input ())
-        print control.service.apply_snapshot (snapshots [n])
+        n = int (input ())
+        print(control.service.apply_snapshot (snapshots [n]))
     except:
         shutdown (monitor)
-- 
2.14.1




More information about the elbe-devel mailing list