Optimize "open" method with context manager

Use opening context manager to open a file.

Change-Id: I4744f3e7650d3d3393c5c019216b241ec77710eb
This commit is contained in:
xiexs 2015-11-27 04:23:06 -05:00
parent 13249545e1
commit a60ec7aa5b
3 changed files with 12 additions and 6 deletions

View File

@ -94,7 +94,8 @@ def _install_ssl_certs(instance, certs):
"changeit\"")
with instance.remote() as r:
for idx, cert in enumerate(certs):
data = open(cert).read()
with open(cert) as cert_fd:
data = cert_fd.read()
r.write_file_to("/tmp/cert.pem", data)
try:
r.execute_command(register_cmd % idx)

View File

@ -318,7 +318,8 @@ class BaseTestCase(base.BaseTestCase):
path = utils.rand_name('test')
data = None
if source:
data = open(source).read()
with open(source) as source_fd:
data = source_fd.read()
self.__upload_to_container(container, path, data)
@ -339,7 +340,8 @@ class BaseTestCase(base.BaseTestCase):
"sudo su - -c \"hdfs dfs -mkdir -p %(path)s \" %(user)s" % {
"path": hdfs_dir, "user": hdfs_username})
hdfs_filepath = utils.rand_name(hdfs_dir + "/file")
data = open(source).read()
with open(source) as source_fd:
data = source_fd.read()
self._run_command_on_node(
inst_ip,
("echo -e \"%(data)s\" | sudo su - -c \"hdfs dfs"
@ -350,7 +352,8 @@ class BaseTestCase(base.BaseTestCase):
return hdfs_filepath
def _create_internal_db_data(self, source):
data = open(source).read()
with open(source) as source_fd:
data = source_fd.read()
id = self.__create_internal_db_data(utils.rand_name('test'), data)
return 'internal-db://%s' % id

View File

@ -49,10 +49,12 @@ def generate_key_pair(key_length=2048):
processutils.execute(*args)
if not os.path.exists(keyfile):
raise ex.SystemError(_("Private key file hasn't been created"))
private_key = open(keyfile).read()
with open(keyfile) as keyfile_fd:
private_key = keyfile_fd.read()
public_key_path = keyfile + '.pub'
if not os.path.exists(public_key_path):
raise ex.SystemError(_("Public key file hasn't been created"))
public_key = open(public_key_path).read()
with open(public_key_path) as public_key_path_fd:
public_key = public_key_path_fd.read()
return private_key, public_key