【问题标题】:Python fabric quotes issuePython 面料报价问题
【发布时间】:2013-07-25 12:07:45
【问题描述】:

我花了将近 30 多分钟的时间来尝试所有可能的不同。终于现在我筋疲力尽了。有人可以帮我解决这个报价问题

def remote_shell_func_execute():
    with settings(host_string='user@XXX.yyy.com',warn_only=True):
            process = run("subprocess.Popen(\["/root/test/shell_script_for_test.sh func2"\],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)")
            process.wait()
            for line in process.stdout.readlines():
                    print(line)

当运行工厂时,我得到了

fab remote_shell_func_execute
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/Fabric-1.6.1-py2.7.egg/fabric/main.py",line 654, in main
docstring, callables, default = load_fabfile(fabfile)
File "/usr/local/lib/python2.7/site-packages/Fabric-1.6.1-py2.7.egg/fabric/main.py",line 165, in load_fabfile
 imported = importer(os.path.splitext(fabfile)[0])
 File "/home/fabfile.py", line 18
process = run("subprocess.Popen(\["/root/test/shell_script_for_test.sh        func2"\],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)")
                                                                           ^
SyntaxError: invalid syntax

【问题讨论】:

    标签: python quotes fabric


    【解决方案1】:

    只需使用单引号字符串。

    run('subprocess.Popen(\["/root/test/shell_script_for_test.sh func2"\],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)')
    

    或者转义内部"

    run("subprocess.Popen(\[\"/root/test/shell_script_for_test.sh func2\"\],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)")
    

    【讨论】:

    • 第一个选项不起作用。收到以下[root@null-000c293cc871.dv6594.homedepot.com] out: /bin/bash: -c: line 0: syntax error near unexpected token ["/root/test/shell_script_for_test.sh func2"],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE'` 第二个选项包含此错误@987654325 @["/root/test/shell_script_for_test.sh func2"],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE'`
    • 你在该命令的其他任何地方都有单引号吗?如果是,那么第二个选项将起作用。
    • @Sathy :这是 Bash 的错误。您的命令不太正确。不幸的是,我对 Linux 了解不多,无法在这方面为您提供更多帮助。错误不是来自 Python。您的 Python 脚本执行良好。
    【解决方案2】:

    转义引号时,转义反斜杠必须直接放在引号字符之前:

    "[\"/..."
    

    或者,对字符串使用单引号,这完全避免了转义的需要:

    '["/...'
    

    【讨论】:

    • 那是一个非常快速的回复。让我试试看。
    • 是引号还是方括号有问题?
    • @Sathy 方括号不需要在字符串中转义 - 只有用于打开/关闭字符串的引号类型需要。只是告诉 Python 字符串没有到此结束。
    • 谢谢。您能告诉我如何将以下内容更改为process = run('subprocess.Popen(["/root/test/shell_script_for_test.sh func2"],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)')
    • @Sathy 那里没有语法问题。您还有另一个单独的问题。
    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    相关资源
    最近更新 更多