带有嵌入式命令的 os.system [英] os.system with embedded commands

查看:64
本文介绍了带有嵌入式命令的 os.system的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经挣扎了很长时间,但仍然无法使这行代码工作:

I've now been struggling a long time and still can't get this line of code working :

os.system('su - postgres -c "psql -c \'ALTER USER postgres WITH ENCRYPTED PASSWORD \\\"{0}\\\";\'"'.format(self.password))

和日志结果:

2013-11-12 19:58:42 ICT ERROR:  syntax error at or near ""password"" at character 45
2013-11-12 19:58:42 ICT STATEMENT:  ALTER USER postgres WITH ENCRYPTED PASSWORD "password";

有什么想法吗?

推荐答案

呃.如果可能,请使用 psycopg2,PostgreSQL 的本机 Python 客户端驱动程序.

Urgh. Please use psycopg2, the native Python client driver for PostgreSQL, if at all possible.

如果您必须使用 psql,请使用 subprocess 模块的 check_call 函数,它更容易和更安全,因为它负责引用给你.

If you must shell out to psql, use the subprocess module's check_call function, which is easier and safer as it takes care of quoting for you.

import subprocess
subprocess.check_call([
    'psql', '-c',
    'ALTER USER postgres WITH ENCRYPTED PASSWORD "{0}";'.format(self.password)
])

os.system 真的应该是 IMO 的最后手段.

os.system should really be a last resort IMO.

这篇关于带有嵌入式命令的 os.system的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆