bootstrap-vz/common/tools.py

61 lines
1.7 KiB
Python
Raw Normal View History

2013-06-27 23:26:29 +02:00
2013-08-13 20:40:16 +02:00
def log_check_call(command, stdin=None):
status, stdout, stderr = log_call(command, stdin)
2013-07-01 22:06:42 +02:00
if status != 0:
from subprocess import CalledProcessError
2013-07-07 21:29:15 +02:00
raise CalledProcessError(status, ' '.join(command), '\n'.join(stderr))
2013-07-13 15:01:21 +02:00
return stdout
2013-07-01 22:06:42 +02:00
2013-08-13 20:40:16 +02:00
def log_call(command, stdin=None):
2013-06-27 23:26:29 +02:00
import subprocess
import select
2013-07-01 22:06:42 +02:00
2013-07-01 22:21:47 +02:00
import logging
2013-07-07 21:29:15 +02:00
from os.path import realpath
command_log = realpath(command[0]).replace('/', '.')
2013-07-01 22:21:47 +02:00
log = logging.getLogger(__name__ + command_log)
2013-08-13 20:40:16 +02:00
if stdin is not None:
2013-07-10 16:33:35 +02:00
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2013-08-13 20:40:16 +02:00
process.stdin.write(stdin+"\n")
2013-07-10 16:33:35 +02:00
process.stdin.flush()
process.stdin.close()
else:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2013-07-07 21:29:15 +02:00
stdout = []
stderr = []
2013-06-27 23:26:29 +02:00
while True:
reads = [process.stdout.fileno(), process.stderr.fileno()]
ret = select.select(reads, [], [])
for fd in ret[0]:
if fd == process.stdout.fileno():
line = process.stdout.readline()
if line != '':
2013-07-01 22:21:47 +02:00
log.debug(line.strip())
2013-07-07 21:29:15 +02:00
stdout.append(line.strip())
2013-06-27 23:26:29 +02:00
if fd == process.stderr.fileno():
line = process.stderr.readline()
if line != '':
2013-07-01 22:21:47 +02:00
log.error(line.strip())
2013-07-07 21:29:15 +02:00
stderr.append(line.strip())
2013-06-27 23:26:29 +02:00
if process.poll() is not None:
2013-07-07 21:29:15 +02:00
return process.returncode, stdout, stderr
def sed_i(file_path, pattern, subst):
from tempfile import mkstemp
from shutil import move
from os import close
import os
temp_fd, temp_path = mkstemp()
mode = os.stat(file_path).st_mode
with open(temp_path, 'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
close(temp_fd)
os.chmod(temp_path, mode)
move(temp_path, file_path)