[英]passing sentence as a argument in subprocess command
I am executing python script inside another script and want to pass two arguments to it 我正在另一个脚本中执行python脚本,并想向其传递两个参数
lines = [line.strip('\n') for line in open('que.txt')]
for l in lines:
print 'my sentence : '
print l
#os.system("find_entity.py") //this also does not work
subprocess.call(" python find_entity.py l 1", shell=True) //this works but l does not considered as sentence which was read
what is the correct approach? 正确的方法是什么?
update: 更新:
lines = [line.strip('\n') for line in open('q0.txt')]
for line_num, line in enumerate(lines):
cmd = ["python", "find_entity.py", line]
subprocess.call(cmd, shell=True)
then it goes to python terminal 然后去python终端
You can use one of string substitution mechanics: 您可以使用以下一种字符串替换机制:
C-style string formatting C样式的字符串格式
in your case it would looks like 在您的情况下,它看起来像
subprocess.call("python find_entity.py %s %d" % (line, line_num))
C#-style string formatting C#样式的字符串格式
subprocess.call("python find_entity.py {} {}".format(line, line_num))
Or, in case with subprocess
library you should pass arguments as list to call
function: 或者,如果使用subprocess
库,则应将参数作为列表传递给call
函数:
subprocess.call(["python", "find_entity.py", line, str(line_num)])
Look at line
and line_num
variables — they pass without any quotes, so they would be passed by value. 查看line
和line_num
变量-它们传递时不带引号,因此它们将按值传递。 This solution is recommended, because it provides more clean and obvious code and provide correct parameter's processing(such as whitespace escaping, etc). 推荐使用此解决方案,因为它提供了更简洁明了的代码并提供了正确的参数处理(例如,空格转义等)。
However, if you want to use shell=True
flag for subprocess.call
, solution with list of args will not work instead of string substitution solutions. 但是,如果要对subprocess.call
使用shell=True
标志,则带有args列表的解决方案将无法代替字符串替换解决方案。 BTW, subprocess
and os
provides all shell powerful options: such as script piping, expanding user home directory(~), etc. So, if you will code big and complicated script you should use python libraries instead of using shell=True
. 顺便说一句, subprocess
和os
提供了所有Shell功能强大的选项:例如脚本管道,扩展用户主目录(〜)等。因此,如果要编写大型而复杂的脚本,则应使用python库,而不要使用shell=True
。
you need the contents of variable l (I renamed it to line), not the string literal "l" 您需要变量l的内容(我将其重命名为line),而不是字符串文字“ l”
for line_num, line in enumerate(lines):
cmd = ["python",
"find_entity.py",
line,
str(line_num)]
subprocess.call(cmd, shell=True)
If you already have the command name and its arguments in separate variables, or already in a list, you almost never want to use shell=True
. 如果命令名称及其参数已经在单独的变量中,或者已经在列表中,则几乎永远不会使用shell=True
。 (It's not illegal, but its behavior is undocumented and generally not what is wanted.) (这不是违法的,但是其行为是无证的,通常不是想要的。)
cmd = ["python", "find_entity.py", line]
subprocess.call(cmd)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.