python subprocess调用bash脚本 - 也需要打印引号

Cha*_*ter 3 python bash subprocess

我遇到了子进程和打印引号的问题.

我的Python脚本接受用户输入,稍微将其混淆 - 我需要它以这种方式将结果发送到bash脚本.

myscript.sh 'var1 == a var2 == b; othervar == c' /path/to/other/files
Run Code Online (Sandbox Code Playgroud)

我挂在哪里就是单引号.Python试图将它们删除.

我用这个来测试.

subprocess.Popen([myscript.sh 'var=11; ignore all' /path/to/files], shell=True, executable="/bin/bash")
Run Code Online (Sandbox Code Playgroud)

返回指向第二个单引号的无效语法.我也尝试了上面没有括号,并在内部使用单引号和内部双引号等.

其他 - 想要的.

正如我上面所说'var == a var == b; othervar == c'是从python脚本(字符串格式)派生的 - 我需要像这样在子进程中调用它.

subprocess.Popen([myscript.sh myvariables /path/to/files], shell=True, executable="/bin/bash")
Run Code Online (Sandbox Code Playgroud)

我只需要像第一个例子那样将单引号括在myvariables的值附近.

有关我正在采用正确方法的地方的指示吗?

谢谢.

Ken*_*der 7

当shell = True传递给Popen时,您将传递在命令行上发送的任何内容.这意味着您的列表应该只有一个元素.例如:

subprocess.Popen(['myscript.sh "var=11; ignore all" /path/to/files'], shell=True, executable="/bin/bash")
Run Code Online (Sandbox Code Playgroud)

或者如果/ path/to/files是Python环境中的变量:

subprocess.Popen(['myscript.sh "var=11; ignore all" %s' % path_to_files], shell=True, executable="/bin/bash")
Run Code Online (Sandbox Code Playgroud)

说过我强烈建议你不要使用shell参数.原因是脆弱.你会得到一个更强大的方法:

subprocess.Popen(["/bin/bash", "myscript.sh", "var=11; ignore all", path_to_files])
Run Code Online (Sandbox Code Playgroud)

请注意,"var = 11; ignore all"作为一个参数传递给您的脚本.如果这些是单独的参数,请将它们分开列表元素.