1212from pepy .pe import PEFile
1313
1414import argparse
15- import urllib2
15+ import urllib . request as request
1616import platform
1717import re
1818import time
4040from zipfile import ZipFile
4141from tarfile import TarFile
4242
43- try :
44- from cStringIO import StringIO
45- except ImportError :
46- from StringIO import StringIO
43+ from io import StringIO
4744
4845from configobj import ConfigObj
4946
@@ -93,7 +90,7 @@ def is_installed():
9390logger .addHandler (handler )
9491
9592def my_excepthook (type_ , value , tback ):
96- output_err = u'' .join ([unicode ( x ) for x in traceback .format_exception (type_ , value , tback )])
93+ output_err = u'' .join ([x for x in traceback .format_exception (type_ , value , tback )])
9794 logger .error (u'{}' .format (output_err ))
9895 sys .__excepthook__ (type_ , value , tback )
9996
@@ -150,10 +147,10 @@ def __init__(self, name='', display_name=None, value=None,
150147 self .get_file_information_from_url ()
151148
152149 def filter_name (self , text ):
153- action = unicode
154- if hasattr ( unicode , self .filter_action ):
155- action = getattr ( unicode , self . filter_action )
156- return action ( unicode ( text ))
150+ if hasattr ( self . filter_action , text ):
151+ action = getattr ( self .filter_action , text )
152+ return action ( text )
153+ return text
157154
158155 def get_file_information_from_url (self ):
159156 if hasattr (self , 'url' ):
@@ -256,17 +253,17 @@ def get_file_bytes(self, version):
256253 elif self .file_ext == '.zip' :
257254 new_bytes = file .read (extract_p )
258255 except KeyError as e :
259- logger .error (unicode (e ))
256+ logger .error (str (e ))
260257 # dirty hack to support old versions of nw
261- if 'no item named' in unicode (e ):
258+ if 'no item named' in str (e ):
262259 extract_path = '/' .join (extract_path .split ('/' )[1 :])
263260 try :
264261 if self .file_ext == '.gz' :
265262 new_bytes = file .extractfile (extract_path ).read ()
266263 elif self .file_ext == '.zip' :
267264 new_bytes = file .read (extract_path )
268265 except KeyError as e :
269- logger .error (unicode (e ))
266+ logger .error (str (e ))
270267
271268 if new_bytes is not None :
272269 fbytes .append ((dest_path , new_bytes ))
@@ -335,7 +332,7 @@ def get_settings(self):
335332 config_io = StringIO (contents )
336333 config = ConfigObj (config_io , unrepr = True ).dict ()
337334 settings = {'setting_groups' : []}
338- setting_items = (config ['setting_groups' ].items () +
335+ setting_items = (list ( config ['setting_groups' ].items () ) +
339336 [('export_settings' , config ['export_settings' ])] +
340337 [('compression' , config ['compression' ])])
341338 for setting_group , setting_group_dict in setting_items :
@@ -351,7 +348,7 @@ def get_settings(self):
351348 for setting_group , setting_group_dict in sgroup_items :
352349 settings ['setting_groups' ].append (settings [setting_group ])
353350
354- self ._setting_items = (config ['setting_groups' ].items () +
351+ self ._setting_items = (list ( config ['setting_groups' ].items () ) +
355352 [('export_settings' , config ['export_settings' ])] +
356353 [('compression' , config ['compression' ])])
357354 config .pop ('setting_groups' )
@@ -405,8 +402,8 @@ def get_versions(self):
405402 union_versions = set ()
406403
407404 for url in self .settings ['version_info' ]['urls' ]:
408- response = urllib2 .urlopen (url )
409- html = response .read ()
405+ response = request .urlopen (url )
406+ html = response .read (). decode ( 'utf-8' )
410407
411408 nw_version = self .get_setting ('nw_version' )
412409
@@ -431,7 +428,7 @@ def get_versions(self):
431428 f .write (v + os .linesep )
432429 f .close ()
433430 except IOError :
434- error = u'' .join ([unicode ( x ) for x in traceback .format_exception (sys .exc_info ()[0 ],
431+ error = u'' .join ([x for x in traceback .format_exception (sys .exc_info ()[0 ],
435432 sys .exc_info ()[1 ],
436433 sys .exc_info ()[2 ])])
437434 self .show_error (error )
@@ -458,7 +455,7 @@ def download_file_with_error_handling(self):
458455 if os .path .exists (setting .save_file_path (version , location )):
459456 os .remove (setting .save_file_path (version , location ))
460457
461- error = u'' .join ([unicode ( x ) for x in traceback .format_exception (sys .exc_info ()[0 ],
458+ error = u'' .join ([x for x in traceback .format_exception (sys .exc_info ()[0 ],
462459 sys .exc_info ()[1 ],
463460 sys .exc_info ()[2 ])])
464461 self .show_error (error )
@@ -498,7 +495,7 @@ def generate_json(self, global_json=False):
498495 if setting .value is not None :
499496 dic [setting_name ] = setting .value
500497 if setting_name == 'keywords' :
501- dic [setting_name ] = re .findall (" \w+" , setting .value )
498+ dic [setting_name ] = re .findall (' \w+' , setting .value )
502499
503500 for setting_name , setting in self .settings ['window_settings' ].items ():
504501 if setting .value is not None :
@@ -515,14 +512,14 @@ def generate_json(self, global_json=False):
515512 dic ['webkit' ][setting_name ] = setting .value
516513
517514 if not global_json :
518- dl_export_items = (self .settings ['download_settings' ].items () +
519- self .settings ['export_settings' ].items () +
520- self .settings ['compression' ].items () +
521- self .settings ['web2exe_settings' ].items ())
515+ dl_export_items = (list ( self .settings ['download_settings' ].items () ) +
516+ list ( self .settings ['export_settings' ].items () ) +
517+ list ( self .settings ['compression' ].items () ) +
518+ list ( self .settings ['web2exe_settings' ].items () ))
522519 else :
523- dl_export_items = (self .settings ['download_settings' ].items () +
524- self .settings ['export_settings' ].items () +
525- self .settings ['compression' ].items ())
520+ dl_export_items = (list ( self .settings ['download_settings' ].items () ) +
521+ list ( self .settings ['export_settings' ].items () ) +
522+ list ( self .settings ['compression' ].items () ))
526523
527524 for setting_name , setting in dl_export_items :
528525 if setting .value is not None :
@@ -539,7 +536,7 @@ def extract_error(self):
539536 @extract_error .setter
540537 def extract_error (self , value ):
541538 if value is not None and not self .quiet and COMMAND_LINE :
542- self ._extract_error = unicode ( value )
539+ self ._extract_error = value
543540 sys .stderr .write (u'\r {}' .format (self ._extract_error ))
544541 sys .stderr .flush ()
545542
@@ -550,7 +547,7 @@ def output_err(self):
550547 @output_err .setter
551548 def output_err (self , value ):
552549 if value is not None and not self .quiet and COMMAND_LINE :
553- self ._output_err = unicode ( value )
550+ self ._output_err = value
554551 sys .stderr .write (u'\r {}' .format (self ._output_err ))
555552 sys .stderr .flush ()
556553
@@ -561,7 +558,7 @@ def progress_text(self):
561558 @progress_text .setter
562559 def progress_text (self , value ):
563560 if value is not None and not self .quiet and COMMAND_LINE :
564- self ._progress_text = unicode ( value )
561+ self ._progress_text = value
565562 sys .stdout .write (u'\r {}' .format (self ._progress_text ))
566563 sys .stdout .flush ()
567564
@@ -624,7 +621,7 @@ def extract_files(self):
624621 if os .path .exists (save_file_path ):
625622 os .remove (save_file_path )
626623 self .extract_error = e
627- self .logger .error (unicode ( self .extract_error ) )
624+ self .logger .error (self .extract_error )
628625 # cannot use GUI in thread to notify user. Save it for later
629626 self .progress_text = '\n Done.\n '
630627 return True
@@ -662,24 +659,12 @@ def make_output_dirs(self):
662659
663660 output_dir = utils .path_join (self .output_dir (), self .project_name ())
664661 if os .path .exists (output_dir ):
665- try :
666- utils .rmtree (output_dir )
667- except OSError as e :
668- error = u'Failed to remove output directory: {}.' .format (output_dir )
669- error += '\n Error recieved: {}' .format (e )
670- self .logger .error (error )
671- self .output_err += error
662+ utils .rmtree (output_dir , onerror = self .remove_readonly )
672663
673664 temp_dir = utils .path_join (TEMP_DIR , 'webexectemp' )
674665
675666 if os .path .exists (temp_dir ):
676- try :
677- utils .rmtree (temp_dir )
678- except OSError as e :
679- error = u'Failed to remove temporary directory: {}.' .format (temp_dir )
680- error += '\n Error recieved: {}' .format (e )
681- self .logger .error (error )
682- self .output_err += error
667+ utils .rmtree (temp_dir , onerror = self .remove_readonly )
683668
684669 self .progress_text = 'Making new directories...\n '
685670
@@ -814,19 +799,13 @@ def make_output_dirs(self):
814799 os .remove (nw_path )
815800
816801 except Exception :
817- error = u'' .join ([unicode ( x ) for x in traceback .format_exception (sys .exc_info ()[0 ],
802+ error = u'' .join ([x for x in traceback .format_exception (sys .exc_info ()[0 ],
818803 sys .exc_info ()[1 ],
819804 sys .exc_info ()[2 ])])
820805 self .logger .error (error )
821806 self .output_err += error
822807 finally :
823- try :
824- utils .rmtree (temp_dir )
825- except OSError as e :
826- error = u'Failed to remove temporary directory: {}.' .format (temp_dir )
827- error += '\n Error recieved: {}' .format (e )
828- self .logger .error (error )
829- self .output_err += error
808+ utils .rmtree (temp_dir , onerror = self .remove_readonly )
830809
831810 def make_desktop_file (self , nw_path , export_dest ):
832811 icon_set = self .get_setting ('icon' )
@@ -860,7 +839,7 @@ def make_desktop_file(self, nw_path, export_dest):
860839 with codecs .open (dfile_path , 'w+' , encoding = 'utf-8' ) as f :
861840 f .write (file_str )
862841
863- os .chmod (dfile_path , 0755 )
842+ os .chmod (dfile_path , 0o755 )
864843
865844 def compress_nw (self , nw_path ):
866845 compression = self .get_setting ('nw_compression_level' )
@@ -884,8 +863,8 @@ def compress_nw(self, nw_path):
884863
885864 if upx_version is not None :
886865 upx_bin = upx_version
887- os .chmod (upx_bin , 0755 )
888- cmd = [upx_bin , '--lzma' , u'-{}' .format (compression .value ), unicode ( nw_path ) ]
866+ os .chmod (upx_bin , 0o755 )
867+ cmd = [upx_bin , '--lzma' , u'-{}' .format (compression .value ), nw_path ]
889868 if platform .system () == 'Windows' :
890869 startupinfo = subprocess .STARTUPINFO ()
891870 startupinfo .dwFlags |= subprocess .STARTF_USESHOWWINDOW
@@ -905,6 +884,16 @@ def compress_nw(self, nw_path):
905884 time .sleep (2 )
906885 output , err = proc .communicate ()
907886
887+ def remove_readonly (self , action , name , exc ):
888+ try :
889+ os .chmod (name , stat .S_IWRITE )
890+ os .remove (name )
891+ except Exception as e :
892+ error = u'Failed to remove file: {}.' .format (name )
893+ error += '\n Error recieved: {}' .format (e )
894+ self .logger .error (error )
895+ self .output_err += error
896+
908897 def copy_files_to_project_folder (self ):
909898 old_dir = CWD
910899 os .chdir (self .project_dir ())
@@ -927,7 +916,7 @@ def copy_files_to_project_folder(self):
927916 def convert_val_to_str (self , val ):
928917 if isinstance (val , (list , tuple )):
929918 return ', ' .join (val )
930- return unicode (val ).replace (self .project_dir ()+ os .path .sep , '' )
919+ return str (val ).replace (self .project_dir ()+ os .path .sep , '' )
931920
932921
933922 def run_script (self , script ):
@@ -1115,9 +1104,9 @@ def download_file(self, path, setting):
11151104 elif tmp_exists and (os .stat (tmp_file ).st_size > 0 ):
11161105 tmp_size = os .stat (tmp_file ).st_size
11171106 headers = {'Range' : 'bytes={}-' .format (tmp_size )}
1118- url = urllib2 .Request (url , headers = headers )
1107+ url = request .Request (url , headers = headers )
11191108
1120- web_file = urllib2 .urlopen (url )
1109+ web_file = request .urlopen (url )
11211110 f = open (tmp_file , 'ab' )
11221111 meta = web_file .info ()
11231112 file_size = tmp_size + int (meta .getheaders ("Content-Length" )[0 ])
@@ -1179,8 +1168,7 @@ def error(self, message):
11791168 sys .exit (2 )
11801169
11811170def unicode_arg (bytestring ):
1182- unicode_string = bytestring .decode (sys .getfilesystemencoding ())
1183- return unicode_string
1171+ return bytestring
11841172
11851173def main ():
11861174 parser = ArgParser (description = ('Command line interface '
@@ -1233,7 +1221,7 @@ def main():
12331221 else :
12341222 if setting .values :
12351223 kwargs .update ({'choices' : setting .values })
1236- setting .description += u' Possible values: {{{}}}' .format (', ' .join ([unicode (x ) for x in setting .values ]))
1224+ setting .description += u' Possible values: {{{}}}' .format (', ' .join ([str (x ) for x in setting .values ]))
12371225 kwargs .update ({'metavar' : '' })
12381226 else :
12391227 kwargs .update ({'metavar' : '<{}>' .format (setting .display_name )})
@@ -1276,7 +1264,7 @@ def main():
12761264 logger .addHandler (handler )
12771265
12781266 def my_excepthook (type_ , value , tback ):
1279- output_err = u'' .join ([unicode ( x ) for x in traceback .format_exception (type_ , value , tback )])
1267+ output_err = u'' .join ([x for x in traceback .format_exception (type_ , value , tback )])
12801268 logger .error (u'{}' .format (output_err ))
12811269 sys .__excepthook__ (type_ , value , tback )
12821270
0 commit comments