Projects/worblehat-old
Projects
/
worblehat-old
Archived
12
0
Fork 0
This repository has been archived on 2024-07-04. You can view files and clone it, but cannot push or open issues or pull requests.
worblehat-old/cli/file_io.py

80 lines
2.1 KiB
Python

import os
import tempfile
import locale
import sys
from exc import WorblehatException
stdout_encoding = locale.getpreferredencoding()
file_encoding = 'utf-8'
output = sys.stdout
# def write_tmpfile(pfix, content, encoding='utf8'):
# file = tempfile.NamedTemporaryFile(prefix=pfix+'-', dir='/tmp', delete=False)
# file.write(content.encode(encoding))
# name = file.name
# file.close()
# return name
def open_tmpfile(prefix):
global output
if output != sys.stdout:
raise WorblehatException('open_tmpfile: Already writing to a file')
tmpfile = tempfile.NamedTemporaryFile(prefix='worblehat-%s-' % prefix,
dir='/tmp',
delete=False)
output = tmpfile
return tmpfile.name
def close_tmpfile():
global output
if output == sys.stdout:
raise WorblehatException('close_tmpfile: No file open')
output.close()
output = sys.stdout
def output_encoding():
if output == sys.stdout:
return stdout_encoding
else:
return file_encoding
def encoding_comment():
return '# -*- coding: %s -*-\n' % file_encoding
def write(data):
if type(data) == unicode:
data = data.encode(output_encoding())
output.write(data)
def write_stderr(data):
if type(data) == unicode:
data = data.encode(output_encoding())
sys.stderr.write(data)
debugging = True
def debug(msg):
if debugging:
write_stderr('DEBUG: %s\n' % msg)
def tmpfile_name():
if output == sys.stdout:
raise WorblehatException('tmpfile_name: No file open')
return output.name
class tmpfile:
def __init__(self, prefix):
self.prefix = prefix
def __enter__(self):
open_tmpfile(self.prefix)
def __exit__(self, exc_type, exc, traceback):
close_tmpfile()
def run_editor(filename):
if os.path.exists(filename):
os.system("%s %s || /usr/bin/env vi %s" %
(os.getenv("EDITOR"), filename, filename))
else:
exit("Error: %s: File does not exist!" % filename)