简体   繁体   中英

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.

No, your problem is that you're using split() to construct the list of arguments to the command to execute. You're also using quotes, which are shell syntax even though you're not invoking a 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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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