蟒蛇子调用bash脚本 - 需要打印出的报价太 [英] python subprocess calling bash script - need to print the quotes out too

查看:157
本文介绍了蟒蛇子调用bash脚本 - 需要打印出的报价太的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与子和印刷报价的一个问题。

I'm having a problem with subprocess and printing quotes.

我的Python脚本接受用户输入,它捣烂了一下周围 - 我需要它把它的结果bash脚本以这种方式

My Python script takes user input, mashes it around a bit - and I need it to send it's results to a bash script in this manner.

myscript.sh 'var1 == a var2 == b; othervar == c' /path/to/other/files

在哪里我就要挂了是单引号。蟒蛇试图撕裂出来。

Where I'm getting hung up on is the single quotes. Python tries to rip them out.

我用这对我的考验。

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

返回第2次单引号无效语法指点。我也试过上面没有括号外使用单引号和双引号内,等等。

which returns an invalid syntax pointing at the 2nd single quote. I've also tried the above without the brackets and using single quotes outside and double quotes inside, etc.

其他 - 会 - 像

正如我说上面的VAR ==一个变种== B: othervar == C'是从python脚本导出(字符串格式) - 我会需要调用,在像这样子

As I was saying above the 'var == a var == b; othervar == c' is derived from the python script (in string format) - and I'll need to call that in the subprocess like this.

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

我只是把周围像第一个例子myvariables价值的单引号。

I just have to put the single quotes around the value of myvariables like the first example.

任何指针,以我要去停止的地方正确的方法?

Any pointers as to where I'm going off the correct method?

感谢您。

推荐答案

在壳= TRUE被传递到POPEN,你通过什么,你会在命令行上发送。这意味着您的列表应该只有一个元素。因此,例如:

When shell=True is passed to Popen, you pass whatever you would send on the command line. That means your list should only have one element. So for example:

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

或者,如果/路径/要/文​​件在你的Python环境变量:

Or if /path/to/files is a variable in your Python environment:

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

说了这么多我的强烈鼓励你不要使用shell参数。原因是脆弱性。你会得到做这样的更强大的方式:

Having said that I STRONGLY encourage you not to use the shell argument. The reason is fragility. You'll get a much more robust way of doing it like this:

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

请注意,VAR = 11;无视一切作为一个参数给脚本传递。如果这些是单独的参数,让他们单独的列表元素。

Note that "var=11; ignore all" is passed as one argument to your script. If those are separate arguments, make them separate list elements.

这篇关于蟒蛇子调用bash脚本 - 需要打印出的报价太的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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