diff --git a/mmgen/altcoins/eth/tx.py b/mmgen/altcoins/eth/tx.py index 51d61b78..b7456c95 100755 --- a/mmgen/altcoins/eth/tx.py +++ b/mmgen/altcoins/eth/tx.py @@ -89,7 +89,8 @@ class EthereumMMGenTX: if getattr(opt,'contract_data',None): m = "'--contract-data' option may not be used with token transaction" assert not 'Token' in type(self).__name__, m - self.usr_contract_data = HexStr(open(opt.contract_data).read().strip()) + with open(opt.contract_data) as fp: + self.usr_contract_data = HexStr(fp.read().strip()) self.disable_fee_check = True async def get_nonce(self): diff --git a/mmgen/cfg.py b/mmgen/cfg.py index d24de8ac..0a9e844e 100755 --- a/mmgen/cfg.py +++ b/mmgen/cfg.py @@ -49,7 +49,8 @@ class CfgFile(object): def __init__(self): self.fn = os.path.join(self.fn_dir,self.fn_base) try: - self.data = open(self.fn).read().splitlines() + with open(self.fn) as fp: + self.data = fp.read().splitlines() except: if self.warn_missing: self.warn_missing_file( div=self.fn, fmt_args=(self.desc,self.fn) ) @@ -61,7 +62,8 @@ class CfgFile(object): if src.data: data = src.data + src.make_metadata() if self.write_metadata else src.data try: - open(self.fn,'w').write('\n'.join(data)+'\n') + with open(self.fn,'w') as fp: + fp.write('\n'.join(data)+'\n') os.chmod(self.fn,0o600) except: die(2,f'ERROR: unable to write to {self.fn!r}') @@ -184,7 +186,8 @@ class CfgFileSampleSys(CfgFileSample): def __init__(self): if os.getenv('MMGEN_TEST_SUITE_CFGTEST'): self.fn = os.path.join(g.data_dir_root,self.test_fn_subdir,self.fn_base) - self.data = open(self.fn).read().splitlines() + with open(self.fn) as fp: + self.data = fp.read().splitlines() else: # self.fn is used for error msgs only, so file need not exist on filesystem self.fn = os.path.join(os.path.dirname(__file__),'data',self.fn_base) diff --git a/mmgen/daemon.py b/mmgen/daemon.py index fb38b526..63061183 100755 --- a/mmgen/daemon.py +++ b/mmgen/daemon.py @@ -107,7 +107,8 @@ class Daemon(Lockable): @property def pid(self): if self.use_pidfile: - return open(self.pidfile).read().strip() + with open(self.pidfile) as fp: + return fp.read().strip() elif self.platform == 'win': """ Assumes only one running instance of given daemon. If multiple daemons are running, @@ -471,7 +472,8 @@ class CoinDaemon(Daemon): if self.test_suite or self.network == 'regtest': if self.cfg_file and not self.flag.keep_cfg_file: - open(f'{self.datadir}/{self.cfg_file}','w').write(self.cfg_file_hdr) + with open(f'{self.datadir}/{self.cfg_file}','w') as fp: + fp.write(self.cfg_file_hdr) if self.use_pidfile and os.path.exists(self.pidfile): # Parity overwrites the data in the existing pidfile without zeroing it first, leading diff --git a/mmgen/led.py b/mmgen/led.py index 28de1a2f..482f9f53 100755 --- a/mmgen/led.py +++ b/mmgen/led.py @@ -98,8 +98,11 @@ class LEDControl: def check_access(fn,desc,init_val=None): try: - iv = init_val or open(fn).read().strip() - open(fn,'w').write(f'{iv}\n') + if not init_val: + with open(fn) as fp: + init_val = fp.read().strip() + with open(fn,'w') as fp: + fp.write(f'{init_val}\n') return True except PermissionError: ydie(1,'\n'+fmt(f""" @@ -119,8 +122,10 @@ class LEDControl: @classmethod def create_dummy_control_files(cls): db = cls.boards['dummy'] - open(db.status,'w').write('0\n') - open(db.trigger,'w').write(db.trigger_states[1]+'\n') + with open(db.status,'w') as fp: + fp.write('0\n') + with open(db.trigger,'w') as fp: + fp.write(db.trigger_states[1]+'\n') def noop(self,*args,**kwargs): pass @@ -134,7 +139,8 @@ class LEDControl: msg(f'led_loop({on_secs},{off_secs})') if not on_secs: - open(self.board.status,'w').write('0\n') + with open(self.board.status,'w') as fp: + fp.write('0\n') while True: if self.ev_sleep(3600): return @@ -143,7 +149,8 @@ class LEDControl: for s_time,val in ((on_secs,255),(off_secs,0)): if self.debug: msg_r(('^','+')[bool(val)]) - open(self.board.status,'w').write(f'{val}\n') + with open(self.board.status,'w') as fp: + fp.write(f'{val}\n') if self.ev_sleep(s_time): if self.debug: msg('\n') @@ -178,4 +185,5 @@ class LEDControl: msg('Stopping LED') if self.board.trigger: - open(self.board.trigger,'w').write(self.board.trigger_states[1]+'\n') + with open(self.board.trigger,'w') as fp: + fp.write(self.board.trigger_states[1]+'\n') diff --git a/mmgen/main_autosign.py b/mmgen/main_autosign.py index 38113cc9..58b7be0e 100755 --- a/mmgen/main_autosign.py +++ b/mmgen/main_autosign.py @@ -326,7 +326,8 @@ def create_key(): desc = f'key file {fn!r}' msg('Creating ' + desc) try: - open(fn,'w').write(kdata+'\n') + with open(fn,'w') as fp: + fp.write(kdata+'\n') os.chmod(fn,0o400) msg('Wrote ' + desc) except: diff --git a/mmgen/util.py b/mmgen/util.py index 660822f1..a04bba49 100755 --- a/mmgen/util.py +++ b/mmgen/util.py @@ -638,7 +638,8 @@ def write_data_to_file( outfile,data,desc='data', # if cmp_data is empty, file can be either empty or non-existent if check_data: try: - d = open(outfile,('r','rb')[bool(binary)]).read() + with open(outfile,('r','rb')[bool(binary)]) as fp: + d = fp.read() except: d = '' finally: diff --git a/scripts/exec_wrapper.py b/scripts/exec_wrapper.py index fdab3fd7..01967cbc 100755 --- a/scripts/exec_wrapper.py +++ b/scripts/exec_wrapper.py @@ -47,7 +47,8 @@ def exec_wrapper_write_traceback(): c = exec_wrapper_get_colors() sys.stdout.write('{}{}'.format(c.yellow(''.join(lines)),c.red(exc))) - open('my.err','w').write(''.join(lines+[exc])) + with open('my.err','w') as fp: + fp.write(''.join(lines+[exc])) def exec_wrapper_end_msg(): if os.getenv('EXEC_WRAPPER_SPAWN') and not os.getenv('MMGEN_TEST_SUITE_DETERMINISTIC'): @@ -61,7 +62,9 @@ exec_wrapper_tstart = time.time() try: sys.argv.pop(0) exec_wrapper_execed_file = sys.argv[0] - exec(open(sys.argv[0]).read()) + with open(sys.argv[0]) as fp: + text = fp.read() + exec(text) except SystemExit as e: if e.code != 0 and not os.getenv('EXEC_WRAPPER_NO_TRACEBACK'): exec_wrapper_write_traceback() diff --git a/scripts/gendiff.py b/scripts/gendiff.py index 5b395fa2..037f8d94 100755 --- a/scripts/gendiff.py +++ b/scripts/gendiff.py @@ -24,7 +24,8 @@ translate = { } def cleanup_file(fn): - data = open(fn).read() + with open(fn) as fp: + data = fp.read() def gen_text(): for line in data.splitlines(): line = re.sub('\r\n','\n',line) # DOS CRLF to Unix LF @@ -32,8 +33,10 @@ def cleanup_file(fn): line = re.sub(r'\s+$','',line) # trailing whitespace yield line ret = list(gen_text()) - open(fn+'.orig','w').write(data) - open(fn,'w').write('\n'.join(ret)) + with open(fn+'.orig','w') as fp: + fp.write(data) + with open(fn,'w') as fp: + fp.write('\n'.join(ret)) return ret cleaned_texts = [cleanup_file(fn) for fn in fns] diff --git a/test/test_py_d/ts_autosign.py b/test/test_py_d/ts_autosign.py index e855e8ef..876c786f 100755 --- a/test/test_py_d/ts_autosign.py +++ b/test/test_py_d/ts_autosign.py @@ -129,7 +129,8 @@ class TestSuiteAutosign(TestSuiteBase): for n in (1,2): bad_tx = joinpath(mountpoint,'tx',f'bad{n}.rawtx') if include_bad_tx and not remove_signed_only: - open(bad_tx,'w').write('bad tx data') + with open(bad_tx,'w') as fp: + fp.write('bad tx data') if not include_bad_tx: try: os.unlink(bad_tx) except: pass diff --git a/test/test_py_d/ts_ethdev.py b/test/test_py_d/ts_ethdev.py index f444ac35..76675166 100755 --- a/test/test_py_d/ts_ethdev.py +++ b/test/test_py_d/ts_ethdev.py @@ -392,7 +392,8 @@ class TestSuiteEthdev(TestSuiteBase,TestSuiteShared): if cp.returncode: die(1,cp.stderr.decode()) keyfile = os.path.join(keystore,os.listdir(keystore)[0]) - return json.loads(open(keyfile).read())['address'] + with open(keyfile) as fp: + return json.loads(fp.read())['address'] def make_genesis(signer_addr,prealloc_addr): return { diff --git a/test/test_py_d/ts_input.py b/test/test_py_d/ts_input.py index c2357985..f71fbd1b 100755 --- a/test/test_py_d/ts_input.py +++ b/test/test_py_d/ts_input.py @@ -113,7 +113,8 @@ class TestSuiteInput(TestSuiteBase): return t def get_passphrase_cmdline(self): - open('test/trash/pwfile','w').write('reference password\n') + with open('test/trash/pwfile','w') as fp: + fp.write('reference password\n') t = self.spawn('test/misc/get_passphrase.py', [ '--usr-randchars=0', '--label=MyLabel', diff --git a/test/unit_tests_d/ut_rpc.py b/test/unit_tests_d/ut_rpc.py index c7b6122e..3768dc92 100755 --- a/test/unit_tests_d/ut_rpc.py +++ b/test/unit_tests_d/ut_rpc.py @@ -16,7 +16,8 @@ def cfg_file_auth_test(proto,d): os.makedirs(d.network_datadir) cf = os.path.join(d.datadir,d.cfg_file) - open(cf,'a').write('\nrpcuser = ut_rpc\nrpcpassword = ut_rpc_passw0rd\n') + with open(cf,'a') as fp: + fp.write('\nrpcuser = ut_rpc\nrpcpassword = ut_rpc_passw0rd\n') d.flag.keep_cfg_file = True d.start() diff --git a/test/unit_tests_d/ut_tx.py b/test/unit_tests_d/ut_tx.py index e2c3b8a9..411df5ce 100755 --- a/test/unit_tests_d/ut_tx.py +++ b/test/unit_tests_d/ut_tx.py @@ -53,7 +53,9 @@ class unit_tests: # New in version 3.3: Support for the unicode legacy literal (u'value') was # reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. # See PEP 414 for more information. - chk = re.subn(r"\bu(['\"])",r"\1",open(fpath).read())[0] # remove Python2 'u' string prefixes from ref files + with open(fpath) as fp: + # remove Python2 'u' string prefixes from ref files + chk = re.subn( r"\bu(['\"])", r'\1', fp.read() )[0] diff = get_ndiff(chk,text) #print('\n'.join(diff)) nLines = len([i for i in diff if i.startswith('-')]) diff --git a/test/unit_tests_d/ut_tx_deserialize.py b/test/unit_tests_d/ut_tx_deserialize.py index 6495ac23..26fbed17 100755 --- a/test/unit_tests_d/ut_tx_deserialize.py +++ b/test/unit_tests_d/ut_tx_deserialize.py @@ -98,7 +98,8 @@ class unit_test(object): self._get_core_repo_root() fn_b = 'src/test/data/tx_valid.json' fn = os.path.join(self.core_repo_root,fn_b) - data = json.loads(open(fn).read()) + with open(fn) as fp: + data = json.loads(fp.read()) print_info(fn_b,'Core test vector') n = 1 for e in data: