Skip to content

Commit 87d18e5

Browse files
authored
Add compatibility with both Python 2 and 3 (#22)
* First version, still need to check all commands * fix error with file conversion * improve configparser stability * new version number
1 parent 6cdbead commit 87d18e5

File tree

10 files changed

+24
-25
lines changed

10 files changed

+24
-25
lines changed

bin/kathara_version.txt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
0.32.0
2-
1+
0.33.0

bin/python/check.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,6 @@
4545
print ("Invalid characters in machine names or link names\n")
4646
sys.exit(1)
4747

48-
if sys.version_info >= (3, 0):
49-
print ("Requires Python 2.x, not Python 3.x\n")
50-
sys.exit(1)
51-
5248
if nc.PLATFORM != nc.WINDOWS:
5349
if pwd.getpwuid(os.getuid()).pw_dir != os.environ['HOME']:
5450
print ("HOME variable is different from the real home directory. This won't allow labs to work.\n")

bin/python/command_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ def run_command_detatched(cmd_line):
55
process = subprocess.Popen(cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
66
# Poll process for new output until finished
77
while True:
8-
nextline = process.stdout.readline()
8+
nextline = process.stdout.readline().decode('utf-8')
99
if nextline == '' and process.poll() is not None:
1010
break
1111
sys.stderr.write(nextline)

bin/python/file_conversion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
def win2linux(filename):
55
c = open(filename).read()
66
c = c[1:] if len(c) > 0 and ord(c[0]) == 0xfeff else c
7-
open(filename, 'wb').write(re.sub(r'\r', '', c))
7+
open(filename, 'wb').write(re.sub(r'\r', '', c).encode('utf-8'))
88

99
def win2linux_all_files_in_dir(some_dir):
1010
for dname, dirs, files in os.walk(some_dir):

bin/python/folder_hash.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,6 @@
2323
lab_path = args.directory.replace('"', '').replace("'", '').replace("//", '/')
2424

2525
if args.print_only and nc.PLATFORM == nc.WINDOWS: #linux still needs the hash for the while statement
26-
print " "
26+
print(" ")
2727
else:
28-
print u.generate_urlsafe_hash(lab_path)
28+
print(u.generate_urlsafe_hash(lab_path))

bin/python/lstart.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@
8282

8383
args, unknown = parser.parse_known_args()
8484

85-
machine_name_args = filter (lambda x: not (x.startswith("--") or x.startswith("-")), unknown)
85+
machine_name_args = list(filter (lambda x: not (x.startswith("--") or x.startswith("-")), unknown))
8686

8787
# applying parameter options (1/3)
8888
title_option = " -T "

bin/python/netkit_commons.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1-
import ConfigParser
1+
try:
2+
import configparser as ConfigParser
3+
except:
4+
import ConfigParser
25
config = ConfigParser.ConfigParser()
3-
import StringIO
6+
from io import StringIO
47
from itertools import chain
58
import re
69
import sys
@@ -30,8 +33,8 @@
3033

3134
def read_config():
3235
tmp_config = ConfigParser.ConfigParser()
33-
ini = '[dummysection]\n' + open(os.path.join(os.environ['NETKIT_HOME'], '..', 'config'), 'r').read()
34-
ini_string = StringIO.StringIO(ini)
36+
ini = u'[dummysection]\n' + open(os.path.join(os.environ['NETKIT_HOME'], '..', 'config'), 'r').read()
37+
ini_string = StringIO(ini)
3538
tmp_config.readfp(ini_string)
3639
conf = {}
3740
for key, value in tmp_config.items('dummysection'):
@@ -95,8 +98,8 @@ def lab_parse(path, force=False):
9598
return ({}, [], {}, {}) # has to get names from last positional args
9699

97100
# reads lab.conf
98-
ini_str = '[dummysection]\n' + open(os.path.join(path, 'lab.conf'), 'r').read()
99-
ini_fp = StringIO.StringIO(ini_str)
101+
ini_str = u'[dummysection]\n' + open(os.path.join(path, 'lab.conf'), 'r').read()
102+
ini_fp = StringIO(ini_str)
100103
config.readfp(ini_fp)
101104

102105
# gets 2 list of keys, one for machines and the other for the metadata
@@ -193,7 +196,7 @@ def create_commands(machines, links, options, metadata, path, execbash=False, no
193196

194197
# writing the network list in the temp file
195198
if not execbash:
196-
if not PRINT: u.write_temp(lab_links_text, u.generate_urlsafe_hash(path) + '_links', PLATFORM, file_mode="w+")
199+
if not PRINT: u.write_temp(lab_links_text, str(u.generate_urlsafe_hash(path)) + '_links', PLATFORM, file_mode="w+")
197200

198201
# generating commands for running the containers, copying the config folder and executing the terminals connected to the containers
199202
if PLATFORM != WINDOWS:
@@ -296,7 +299,7 @@ def create_commands(machines, links, options, metadata, path, execbash=False, no
296299
# writing the container list in the temp file
297300
if not no_machines_tmp:
298301
if not execbash:
299-
if not PRINT: u.write_temp(lab_machines_text, u.generate_urlsafe_hash(path) + '_machines', PLATFORM)
302+
if not PRINT: u.write_temp(lab_machines_text, str(u.generate_urlsafe_hash(path)) + '_machines', PLATFORM)
300303

301304

302305
# for each machine we have to get the machine.startup file and insert every non empty line as a string inside an array of exec commands. We also replace escapes and quotes

bin/python/print_metadata.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525
(_,_,_, metadata) = nc.lab_parse(lab_path)
2626

2727
if not args.print_only:
28-
print "========================= Starting Lab =========================="
28+
print("========================= Starting Lab ==========================")
2929
if len(metadata.items()) >= 1:
3030
for key, value in metadata.items():
31-
print '{message: <20}'.format(message=key+":") + value
32-
print "================================================================="
31+
print('{message: <20}'.format(message=key+":") + value)
32+
print("=================================================================")

bin/python/utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
import hashlib
33
import re
44
import os
5+
import functools
56
try:
67
import pwd
78
except ImportError: #windows
89
pass
910

1011
def generate_urlsafe_hash(string):
11-
return base64.urlsafe_b64encode(hashlib.md5(string).digest())[:-2]
12+
return base64.urlsafe_b64encode(hashlib.md5(string.encode('utf-8')).digest())[:-2]
1213

1314
# helper functions for natural sorting
1415
def atoi(text):
@@ -17,7 +18,7 @@ def natural_keys(text):
1718
return [ atoi(c) for c in re.split('(\d+)', text) ]
1819

1920
def replace_multiple_items(repls, string):
20-
return reduce(lambda a, kv: a.replace(*kv), repls, string)
21+
return functools.reduce(lambda a, kv: a.replace(*kv), repls, string)
2122

2223
# writes the temporary files in NETKIT_HOME/temp
2324
def write_temp(text, filename, mode="linux", file_mode="a+"):

bin/python/vstart.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,4 +249,4 @@ def lstart_command_writer():
249249
else:
250250
start_new_machine()
251251

252-
print lstart_command_writer()
252+
print(lstart_command_writer())

0 commit comments

Comments
 (0)