开发者

python os.execvp() trying to display mysql tables gives 1049 error - Unknown database error

开发者 https://www.devze.com 2022-12-27 08:04 出处:网络
I have a question related to MySQL and Python. This command works on the shell, but not when I use os.execvp.

I have a question related to MySQL and Python.

This command works on the shell, but not when I use os.execvp.

$./mysql -D test -e "show tables"

+----------------+
| Tables_in_test |
+----------------+
| sample         |
+---------开发者_StackOverflow-------+

The corresponding piece of code in python would be

def execute():
    args = []
    args.extend(sys.argv[1:])
    args.extend([MYSQL, '-D test -e "show tables"'])
    print args
    os.execvp(args[0], args)
    child_pid = os.fork()
    if child_pid == 0:
        os.execvp(args[0], args)
    else:
        os.wait()

The output of this is:

[./mysql', '-D test -e "show tables"']
ERROR 1049 (42000): Unknown database ' test -e "show tables"'

I am not sure if this is a problem with the Python syntax or not. Also, the same command works with an os.system call.

os.system(MYSQL + ' -D test -e "show tables"')

Please let me know how to get this working.


Each of your separate parameters needs to be a separate element in the list of parameters.

args.extend([MYSQL, '-D test', '-e "show tables"'])


Try:

args.extend([MYSQL, '-D', 'test', '-e', 'show tables'])

You might also be interested in the subprocess module if you weren't aware of it:

>>> import subprocess as subp
>>> print subp.Popen(["mysql", '-D', 'mysql', '-e', 'show tables'], stdout=subp.PIPE).communicate()[0]
Tables_in_mysql
columns_priv
db
func
help_category
help_keyword
help_relation
...

Or just subp.call([MYSQL, ...]) and you don't have to fork+exec yourself, exit status is the return value IIRC.

0

精彩评论

暂无评论...
验证码 换一张
取 消