Home > Software design >  Python init db2cmd and interact with DB2
Python init db2cmd and interact with DB2

Time:11-30

How is it possible to initiate DB2 command line enviroment (Windows) and run DB2 shell EXPORT command from the Python script with waiting for results and error processing?

I tried to run

  process = subprocess.call(or run)(["db2cmd", "./export.bat"], 
                                    shell=True, 
                                    stdin=subprocess.PIPE, 
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE, 
                                    text=True)

OR

  process = subprocess.run(or Popen)(["db2cmd", 
                            "db2 connect to SAMPLE user XXX using XXXXX"
                             " & db2 EXPORT TO STAFF.ixf OF IXF SELECT * FROM STAFF"])              

it works BUT

  1. Main Python script does not wait while DB2 Export is finished - it runs DB2CMD in the separate CMD window and ternimates immediately. DB2CMD with Export continues to run separately;
  2. All output streams are empty - I can't get any errors/results in this way.

What is the best appoach for Pyhton 3.8 script to

  1. Initialize DB2 command line enviroment;

  2. Connect to DB2 database;

  3. Run EXPORT command and wait the results?

    And in case of the error - re-connect to DB and re-run the export once again.

*Using ibm_db does not fit due big tables and complex data.

CodePudding user response:

@mao answer helped, thanks!

  1. Add this at the beginning of the EXPORT script BAT file (what is the magic symbols?)

      set DB2CLP=**$$**
    
  2. In Pyhton script use 'call'. Pyhton runs and waits the completion of the EXPORT BAT

    subprocess.call("\\path\\to\\export.bat" , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True )
    
  3. Parse text output for errors.

  • Related