如何使用python 2在os.system命令中转义/使用单引号?

问题描述 投票:0回答:2

我已经构建了一个小脚本,它运行一个名为imapsync的简单shell实用程序,带有一堆从字典中获取的变量,命令如下:

os.system("imapsync --host1 %s --user1 %s --password1 '%s' --host2 %s --user2 %s --password2 '%s' --ssl1 --no-modulesversion --ssl2" % (fromHost, emails, passwords, toHost, emails, passwords))

这笔交易是密码通常包含特殊字符,例如:djDJS * ^ %%% ^&)

这个imapsync工具允许这样的字符用单引号括起来:'djDJS * ^ %%% ^&)'

我试图实现的是在命令中发布单引号本身..我试过“'”,反引号 - ``,转义引号 - \'\',用单引号括起命令,到目前为止没有任何效果

python escaping quotes
2个回答
0
投票

在查看了imapsync的文档之后,我找到了包含passwords in double quotes within single quotes to avoid common problems的建议。

由于您已经使用双引号启动字符串,因此必须使用反斜杠\"来转义密码周围的双引号。

您还可以做两件事来使代码更好。首先,您可以使用.format syntax for string formatting而不是旧的%语法。

第二次用os.system取代subprocess.Popen。这允许您将命令字符串拆分为所有参数的列表,这看起来更清晰。

你的新代码看起来像

import subprocess

args = [
  "imapsync",
  "--host1",
  fromHost,
  "--user1",
  emails,
  "--password1",
  "'\"{}\"'".format(passwords),
  "--host2",
  toHost,
  "--user2",
  emails,
  "--password2",
  "'\"{}\"'".format(passwords),
  "--ssl1",
  "--no-modulesversion",
  "--ssl2"
]

p = subprocess.Popen(args, stdout=subprocess.PIPE)

output = p.communicate()[0]

print(output)

在此示例中,Popen.communicate用于将imapsync命令的输出收集为字符串。 communicate方法返回一个元组,子进程的输出为stdoutstderr流。

如果您还想从子进程读取stderr的输出,请按如下所示更改代码:

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

output, errors = p.communicate()

print(output)
print(errors)

-1
投票

在Python中传递字符串参数的最佳格式是使用格式字符串方法。你可以这样做:

line_command = "imapsync --host1 {fromHost} --user1 {emails} --password1 '\"{passwords}\"' --host2 {toHost} --user2 {emails} --password2 '\"{passwords}\"' --ssl1 --no-modulesversion --ssl2".format(fromHost=fromHost, emails=emails, passwords=passwords, toHost=toHost)
os.system(line_command)
© www.soinside.com 2019 - 2024. All rights reserved.