Python os.close() Examples
The following are 30
code examples of os.close().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
os
, or try the search function
.
Example #1
Source File: device.py From Paradrop with Apache License 2.0 | 10 votes |
def update(ctx): """ Update the chute from the working directory. """ url = ctx.obj['chute_url'] headers = {'Content-Type': 'application/x-tar'} if not os.path.exists("paradrop.yaml"): raise Exception("No paradrop.yaml file found in working directory.") with tempfile.TemporaryFile() as temp: tar = tarfile.open(fileobj=temp, mode="w") for dirName, subdirList, fileList in os.walk('.'): for fname in fileList: path = os.path.join(dirName, fname) arcname = os.path.normpath(path) tar.add(path, arcname=arcname) tar.close() temp.seek(0) res = router_request("PUT", url, headers=headers, data=temp) data = res.json() ctx.invoke(watch, change_id=data['change_id'])
Example #2
Source File: server.py From BASS with GNU General Public License v2.0 | 8 votes |
def whitelist_add(): log.info("whitelist_add called") try: file_ = request.files["file"] handle, filename = tempfile.mkstemp() os.close(handle) file_.save(filename) data = request.get_json() if data and "functions" in data: functions = data["functions"] else: functions = None bass.whitelist_add(filename, functions) os.unlink(filename) except KeyError: log.exception("") return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400) return jsonify(message = "OK")
Example #3
Source File: _gdb.py From ALF with Apache License 2.0 | 7 votes |
def _symbolize(target, output, tool, exp_opt): fd, tmp_log = tempfile.mkstemp(prefix="%s_log" % tool, suffix=".txt", dir=".") try: os.write(fd, output) finally: os.close(fd) try: result = _common.run([TOOL_GDB, "-batch", "-nx", "-ex", "set python print-stack full", "-ex", "py import exploitable", "-ex", "exploitable -m %s %s" % (exp_opt, tmp_log), "-ex", "quit", target], timeout=180) finally: _common.delete(tmp_log) if result.classification == _common.TIMEOUT: raise RuntimeError("Timed out while processing %s output:\n%s" % (tool, output)) result.backtrace, result.classification = _process_gdb_output(result.text) result.text = _common._limit_output_length(result.text) if result.classification == _common.NOT_AN_EXCEPTION: raise RuntimeError("Failed to process %s output:\n%s" % (tool, output)) return result
Example #4
Source File: misc.py From rtp_cluster with BSD 2-Clause "Simplified" License | 6 votes |
def daemonize(logfile = None): # Fork once if os.fork() != 0: os._exit(0) # Create new session os.setsid() if os.fork() != 0: os._exit(0) os.chdir('/') fd = os.open('/dev/null', os.O_RDWR) os.dup2(fd, sys.__stdin__.fileno()) if logfile != None: fake_stdout = open(logfile, 'a', 1) sys.stdout = fake_stdout sys.stderr = fake_stdout fd = fake_stdout.fileno() os.dup2(fd, sys.__stdout__.fileno()) os.dup2(fd, sys.__stderr__.fileno()) if logfile == None: os.close(fd)
Example #5
Source File: wicc_control.py From WiCC with GNU General Public License v3.0 | 6 votes |
def open_cracked_passwords(self): """ Opens the cracked passwords file. :author: Pablo Sanz Alguacil """ try: self.show_message("Opening passwords file") passwords = self.local_folder + "/" + self.passwords_file_name open(passwords, 'r').close() # just to raise an exception if the file doesn't exists command = ['xdg-open', passwords] thread = threading.Thread(target=self.execute_command, args=(command,)) thread.start() except FileNotFoundError: self.show_warning_notification("No stored cracked networks. You need to do and finish an attack")
Example #6
Source File: tarfile.py From jawfish with MIT License | 6 votes |
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'.") try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") fileobj = bz2.BZ2File(fileobj or name, mode, compresslevel=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (IOError, EOFError): fileobj.close() raise ReadError("not a bzip2 file") t._extfileobj = False return t
Example #7
Source File: wicc_control.py From WiCC with GNU General Public License v3.0 | 6 votes |
def stop_running(self): """ Stops the program execution. Notifies the view to finish itself, then deletes the reference. :return: none :Author: Miguel Yanes Fernández """ try: self.stop_scan() self.semGeneral.release() self.view.reaper_calls() self.show_message("\n\n\tClossing WiCC ...\n\n") os.close(2) # block writing to stderr del self.view self.running_stopped = True exit(0) except: raise SystemExit
Example #8
Source File: packetselector.py From XFLTReaT with MIT License | 6 votes |
def replace_client(self, old_client, new_client): if old_client in self.clients: self.clients.remove(old_client) self.clients.append(new_client) try: old_client.get_pipe_w_fd().close() except: pass try: old_client.get_pipe_r_fd().close() except: pass try: socket.close(old_client.get_socket()) except: pass # removing client from the client list
Example #9
Source File: extractor.py From firmanal with MIT License | 6 votes |
def update_database(self, field, value): """ Update a given field in the database. """ ret = True if self.database: try: cur = self.database.cursor() cur.execute("UPDATE image SET " + field + "='" + value + "' WHERE id=%s", (self.tag, )) self.database.commit() except BaseException: ret = False traceback.print_exc() self.database.rollback() finally: if cur: cur.close() return ret
Example #10
Source File: local.py From S4 with GNU General Public License v3.0 | 6 votes |
def put(self, key, sync_object, callback=None): path = os.path.join(self.path, key) self.ensure_path(path) BUFFER_SIZE = 4096 fd, temp_path = tempfile.mkstemp() try: with open(temp_path, "wb") as fp_1: while True: data = sync_object.fp.read(BUFFER_SIZE) fp_1.write(data) if callback is not None: callback(len(data)) if len(data) < BUFFER_SIZE: break shutil.move(temp_path, path) except Exception: os.remove(temp_path) raise finally: os.close(fd) self.set_remote_timestamp(key, sync_object.timestamp)
Example #11
Source File: pydoc.py From jawfish with MIT License | 5 votes |
def pipepager(text, cmd): """Page through text by feeding it to another program.""" pipe = os.popen(cmd, 'w') try: pipe.write(text) pipe.close() except IOError: pass # Ignore broken pipes caused by quitting the pager program.
Example #12
Source File: misc.py From pyscf with Apache License 2.0 | 5 votes |
def __exit__(self, type, value, traceback): sys.stdout.flush() os.dup2(self.bak_stdout_fd, self.old_stdout_fileno) self.fnull.close() # from pygeocoder # this decorator lets me use methods as both static and instance methods # In contrast to classmethod, when obj.function() is called, the first # argument is obj in omnimethod rather than obj.__class__ in classmethod
Example #13
Source File: tarfile.py From jawfish with MIT License | 5 votes |
def __del__(self): if hasattr(self, "closed") and not self.closed: self.close()
Example #14
Source File: support.py From jawfish with MIT License | 5 votes |
def create_empty_file(filename): """Create an empty file. If the file already exists, truncate it.""" fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) os.close(fd)
Example #15
Source File: support.py From jawfish with MIT License | 5 votes |
def start(self): try: f = open(self.procfile, 'r') except OSError as e: warnings.warn('/proc not available for stats: {}'.format(e), RuntimeWarning) sys.stderr.flush() return watchdog_script = findfile("memory_watchdog.py") self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script], stdin=f, stderr=subprocess.DEVNULL) f.close() self.started = True
Example #16
Source File: misc.py From pyscf with Apache License 2.0 | 5 votes |
def __exit__(self, type, value, traceback): sys.stdout.flush() self.ftmp.file.seek(0) self._contents = self.ftmp.file.read() self.ftmp.close() os.dup2(self.bak_stdout_fd, self.old_stdout_fileno) os.close(self.bak_stdout_fd)
Example #17
Source File: tarfile.py From jawfish with MIT License | 5 votes |
def close(self): os.close(self.fd)
Example #18
Source File: misc.py From pyscf with Apache License 2.0 | 5 votes |
def __del__(self): try: self.close() except AttributeError: # close not defined in old h5py pass except ValueError: # if close() is called twice pass except ImportError: # exit program before de-referring the object pass
Example #19
Source File: local.py From S4 with GNU General Public License v3.0 | 5 votes |
def flush_index(self, compressed=True): if compressed: logger.debug("Using gzip encoding for writing index") method = gzip.open else: logger.debug("Using plaintext encoding for writing index") method = open fd, temp_path = tempfile.mkstemp() with method(temp_path, "wt") as fp: json.dump(self.index, fp) os.close(fd) shutil.move(temp_path, self.index_path())
Example #20
Source File: pydoc.py From jawfish with MIT License | 5 votes |
def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w', encoding='utf-8') file.write(page) file.close() print('wrote', name + '.html') except (ImportError, ErrorDuringImport) as value: print(value)
Example #21
Source File: pydoc.py From jawfish with MIT License | 5 votes |
def tempfilepager(text, cmd): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() file = open(filename, 'w') file.write(text) file.close() try: os.system(cmd + ' "' + filename + '"') finally: os.unlink(filename)
Example #22
Source File: tempfile.py From jawfish with MIT License | 5 votes |
def __del__(self): self.close() # Need to trap __exit__ as well to ensure the file gets # deleted when used in a with statement
Example #23
Source File: pydoc.py From jawfish with MIT License | 5 votes |
def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (None, None)) if lastupdate is None or lastupdate < mtime: try: file = tokenize.open(filename) except IOError: # module can't be opened, so skip it return None binary_suffixes = importlib.machinery.BYTECODE_SUFFIXES[:] binary_suffixes += importlib.machinery.EXTENSION_SUFFIXES[:] if any(filename.endswith(x) for x in binary_suffixes): # binary modules have to be imported file.close() if any(filename.endswith(x) for x in importlib.machinery.BYTECODE_SUFFIXES): loader = importlib.machinery.SourcelessFileLoader('__temp__', filename) else: loader = importlib.machinery.ExtensionFileLoader('__temp__', filename) try: module = loader.load_module('__temp__') except: return None result = (module.__doc__ or '').splitlines()[0] del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result
Example #24
Source File: shutil.py From jawfish with MIT License | 5 votes |
def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extractall(extract_dir) finally: tarobj.close()
Example #25
Source File: shutil.py From jawfish with MIT License | 5 votes |
def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % filename) zip = zipfile.ZipFile(filename) try: for info in zip.infolist(): name = info.filename # don't extract absolute paths or ones with .. in them if name.startswith('/') or '..' in name: continue target = os.path.join(extract_dir, *name.split('/')) if not target: continue _ensure_directory(target) if not name.endswith('/'): # file data = zip.read(info.filename) f = open(target, 'wb') try: f.write(data) finally: f.close() del data finally: zip.close()
Example #26
Source File: tempfile.py From jawfish with MIT License | 5 votes |
def close(self): self._file.close()
Example #27
Source File: tempfile.py From jawfish with MIT License | 5 votes |
def __exit__(self, exc, value, tb): self._file.close() # file protocol
Example #28
Source File: tempfile.py From jawfish with MIT License | 5 votes |
def TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix="", prefix=template, dir=None): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newline argument to io.open (default None) The file is created as mkstemp() would do it. Returns an object with a file-like interface. The file has no name, and will cease to exist when it is closed. """ if dir is None: dir = gettempdir() flags = _bin_openflags (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) try: _os.unlink(name) return _io.open(fd, mode, buffering=buffering, newline=newline, encoding=encoding) except: _os.close(fd) raise
Example #29
Source File: tempfile.py From jawfish with MIT License | 5 votes |
def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix="", prefix=template, dir=None, delete=True): """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). 'buffering' -- the buffer size argument to io.open (default -1). 'encoding' -- the encoding argument to io.open (default None) 'newline' -- the newline argument to io.open (default None) 'delete' -- whether the file is deleted on close (default True). The file is created as mkstemp() would do it. Returns an object with a file-like interface; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed unless the 'delete' argument is set to False. """ if dir is None: dir = gettempdir() flags = _bin_openflags # Setting O_TEMPORARY in the flags causes the OS to delete # the file when it is closed. This is only supported by Windows. if _os.name == 'nt' and delete: flags |= _os.O_TEMPORARY (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) file = _io.open(fd, mode, buffering=buffering, newline=newline, encoding=encoding) return _TemporaryFileWrapper(file, name, delete)
Example #30
Source File: tempfile.py From jawfish with MIT License | 5 votes |
def close(self): if not self.close_called: self.close_called = True self.file.close() if self.delete: self.unlink(self.name)