[go: up one dir, main page]

File: redirection.py

package info (click to toggle)
sclapp 0.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 312 kB
  • ctags: 464
  • sloc: python: 2,916; makefile: 35
file content (47 lines) | stat: -rw-r--r-- 1,688 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Copyright (c) 2005-2007 Forest Bond.
# This file is part of the sclapp software package.
# 
# sclapp is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 2 as published by the Free
# Software Foundation.
# 
# A copy of the license has been included in the COPYING file.

import sys, os, types

from sclapp import error_output

def _dup(n, f, flags = None):
    os.close(n)
    try:
        return os.dup(f.fileno())
    except (AttributeError, TypeError):
        try:
            return os.dup(f)
        except TypeError:
            try:
                return os.open(f, flags)
            except TypeError:
                raise TypeError, (
                  'f is neither a usable file-like object, '
                  'an integer file descriptor, nor a filename.'
                )

def redirectFds(stdin = None, stdout = None, stderr = None):
    '''Redirects the standard I/O file descriptors for the current process.
    stdin, stdout, and stderr can be either a filename, an fd (integer), or
    None (to indicate no redirection).
    '''
    pid = os.getpid()
    if stdin is not None:
        error_output._printSclappDebug(
          u'pid %u: redirecting stdin to %s' % (pid, stdin))
        _dup(0, stdin, os.O_RDONLY)
    if stdout is not None:
        error_output._printSclappDebug(
          u'pid %u: redirecting stdout to %s' % (pid, stdout))
        _dup(1, stdout, os.O_RDWR | os.O_APPEND | os.O_CREAT)
    if stderr is not None:
        error_output._printSclappDebug(
          u'pid %u: redirecting stderr to %s' % (pid, stderr))
        _dup(2, stderr, os.O_RDWR | os.O_APPEND | os.O_CREAT)