【问题标题】:How to display single quotes inside double quotes in string in python如何在python中的字符串中的双引号内显示​​单引号
【发布时间】:2017-04-18 12:08:07
【问题描述】:

我知道这是一个非常基本的问题,但无法将其框定出来。

我需要在脚本中执行一个自定义的基于 python 命令的命令。

ex:
below is the actual commands.
command-dist --host='server1' -- cmd -- 'command1;command2'

我需要在我的 python 脚本中使用这个命令 形成我的脚本,这个命令需要在远程服务器上执行

我需要在我的脚本中使用这种命令格式

cmd="ssh -q %s "command-dist --host=%s -- cmd -- 'cmd1;cmd2'"" %(host1,host2)

但由于引号导致上述失败,尝试了多种方法仍然没有运气。

When I tried this way
cmd="ssh -q %s \"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\"" %(host1,host2)

I don't under why back slashes are appearing before and after cmd1;cmd2?
This is what I am not getting.
cmd
'ssh -q %s "command-dist --host=%s -- cmd -- /'cmd1;cmd2'/""' %(host1,host2)

请帮助我如何获得上述值

【问题讨论】:

    标签: python linux python-2.7 shell


    【解决方案1】:

    这个

    cmd="ssh -q %s "command-dist --host=%s -- cmd -- 'cmd1;cmd2'"" %(host1,host2)
    

    被Python理解为

    cmd = <some string>command-dist --host=%s -- cmd -- 'cmd1;cmd2'<some string>
    

    因为您在内部和外部使用相同的引号。 尝试使用反斜杠转义内部引号:

    cmd="ssh -q %s \"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\"" %(host1,host2)
    

    除此之外,您应该使用subprocess 模块并将您的命令作为列表提供给subprocess.Popen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      相关资源
      最近更新 更多