Search Postgresql Archives

Re: running pg_dump from python

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

Erik Jones <ejones@xxxxxxxxxxxxxx> writes:

> On Jun 15, 2009, at 5:17 AM, Jasen Betts wrote:
>
>> On 2009-06-14, Garry Saddington <garry@xxxxxxxxxxxxxxxxxxxx> 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

-- 
Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux