简体   繁体   English

我如何转义大括号中的字符串以馈送给子进程

[英]How can I escape braces in string to be fed to sub process

    import subprocess
    profile_val = 'ishan'
    cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update' + ' ' + profile_val)
    subprocess.call(cmd.split())

It not escaping braces in {likes} and treats like as separate part command and fails. 它不会在{likes}中转义大括号,并且像单独的部分命令一样对待并失败。

No, your problem is that you're using split() to construct the list of arguments to the command to execute. 不,您的问题是您正在使用split()构造要执行的命令的参数列表。 You're also using quotes, which are shell syntax even though you're not invoking a shell. 您还使用了引号,引号是shell语法,即使您不调用shell也是如此。

Just use an array in the first place, so not to have to split: 只是首先使用一个数组,所以不必拆分:

cmd = ('instaloader', '--post-metadata-txt={likes} likes, {comments} comments, {caption}', '--login=blabla_id', '--fast-update', profile_val)
subprocess.call(cmd)

Stephane Chazelas gives the best solution but if you have to split shell-like command you can use shlex. Stephane Chazelas提供了最佳解决方案,但是如果您必须拆分类似于shell的命令,则可以使用shlex。

import subprocess
import shlex
profile_val = 'ishan'
cmd = 'instaloader --post-metadata-txt="{likes} likes, {comments} comments, {caption}" --login=blabla_id --fast-update "' + profile_val + '"'
subprocess.call(shlex.split(cmd))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM