[Tutor] os.system(mysql) (Was help)

dman dsh8290@rit.edu
Thu, 1 Nov 2001 07:43:38 -0500


On Thu, Nov 01, 2001 at 04:24:36AM -0700, Jackson wrote:
| This reply got me wondering about running mysql threw the backdoor?
| 
| >| 
| >| import os
| >| os.system("vim file")
| >
| ><wide grin>  I like that approach :-).
| 
| I installed Python and Mysql from binaries on a Sun E6500 at work,
| but for some reason when ever I try to compile any thing I get an
| gcc error message math.h or iso/math.h not found( GCC was installed
| from binary also)?
| 
| >From the shell we can exicute one following to pass a sql script
| to mysql:
| 
| mysql dbmame -u -p -e sql_script_file
| mysql dbname -u -p < sql_script_file
| 
| 
| What I want to do is:
| 
| ------------- Python script -----------
| #!/usr/bin/python
| import os
| 
| hostname = raw_input("Enter hostname: ")
| ipaddr = raw_input("Enter IP address: ")
| 
| query="insert into text(hostname,ipaddr)
|                 valuess('hostname','ipaddr')"
| os.system(" mysql dbname -u -p -e query)
| 
| -----------------
| 
| Does that make any sense *grin*

It is doable, though likely not optimal.  As far as performance is
concerned, you are starting two more processes (a shell and mysql).
More importantly, you have the potential for quoting issues.  When you
call os.system() a shell (probably /bin/sh on *nix systems and
command.com or cmd.exe on win*) is started and it is passed the string
as a commend.  The shell then has to interpret that string, so any
special characters (backslashes, spaces, quotes, etc.) must be escaped
or quoted such that the shell interprets them correctly.  Then the
shell executes the command, and it interprets any arguments passed to
it.  Thus if you wanted to insert the string "\" (a single backslash)
into your db, you'd have to write something like
    "\\\\\\\\"
The reason is, you have to escape each backslash for python.  Thus you
have \\.  Then you have to escape each of those backslashes for the
shell, \\\\.  Then, I assume, mysql will require the backslash to be
escaped, so you need 2 backslashes going into mysql (double what went
into the shell).

So, while what you proposed above is doable, I'd recommend using the
programmatic API instead.  The main difference between accessing a db
and editing a file is that db's have APIs while most text editors
don't.  You could write a text editor, but why?

HTH,
-D