Re: running pg_dump from python

Поиск
Список
Период
Сортировка
От Dimitri Fontaine
Тема Re: running pg_dump from python
Дата
Msg-id 874ou8wjik.fsf@hi-media-techno.com
обсуждение исходный текст
Ответ на Re: running pg_dump from python  (Erik Jones <ejones@engineyard.com>)
Список pgsql-general
Hi,

Erik Jones <ejones@engineyard.com> writes:

> On Jun 15, 2009, at 5:17 AM, Jasen Betts wrote:
>
>> On 2009-06-14, Garry Saddington <garry@schoolteachers.co.uk> wrote:
>>> def backup():
>>>    import  os
>>>    os.popen("c:/scholarpack/postgres/bin/pg_dump scholarpack  >
>>> c:/scholarpack/ancillary/scholarpack.sql")
>>
>> are you sure you're using os.popen correctly?
>> you don't appear to be waiting for the pg_dump process to finish.
>
> Right, the popen stuff should be something like:
>
> p = os.popen("c:/scholarpack/postgres/bin/pg_dump scholarpack  > c:/
> scholarpack/ancillary/scholarpack.sql 2> c:/scholarpack/ancillary/
> dump.err")
> status = p.close()
>
> Then check status to see if the command was successful or not.

Well, use subprocess:

def run_command(command, expected_retcodes = 0, stdin = None):
    """run a command and raise an exception if retcode not in expected_retcode"""

    # we want expected_retcode to be a tuple but will manage integers
    if type(expected_retcodes) == type(0):
        expected_retcodes = (expected_retcodes,)

    # we want the command to be a list, but accomodate when given a string
    cmd = command
    if type(cmd) == type('string'):
        cmd = shlex.split(command)

    proc = subprocess.Popen(cmd,
                            stdin  = stdin,
                            stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE)

    out, err = proc.communicate()

    if proc.returncode not in expected_retcodes:
        # when nothing gets to stderr, add stdout to Detail
        if err.strip() == '':
            err = out

        mesg  = 'Error [%d]: %s' % (proc.returncode, command)
        mesg += '\nDetail: %s' % err
        raise Exception, mesg

    return proc.returncode, out, err


Regards,
--
dim

В списке pgsql-general по дате отправления:

Предыдущее
От: Grzegorz Jaśkiewicz
Дата:
Сообщение: Re: Graphical representation of query plans
Следующее
От: Dario Teixeira
Дата:
Сообщение: Information about columns