How to use subprocess when multiple arguments contain spaces?

后端 未结 10 2159

I\'m working on a wrapper script that will exercise a vmware executable, allowing for the automation of virtual machine startup/shutdown/register/deregister actions. I\'m t

相关标签:
10条回答
  • 2021-01-07 18:40

    One problem is that if the command is surrounded with quotes and doesn't have spaces, that could also confuse the shell.

    So I do this:

    if ' ' in raw_cmd:
        fmt = '"%s"'
    else:
        fmt = '%s'
    
    cmd = fmt % raw_cmd
    
    0 讨论(0)
  • 2021-01-07 18:47

    If you have spaces in the path, the easiest way I've found to get them interpreted properly is this.

    subprocess.call('""' + path + '""')
    

    I don't know why exactly it needs double double quotes, but that is what works.

    0 讨论(0)
  • 2021-01-07 18:47

    Why are you using r""? I believe that if you remove the "r" from the beginning, it will be treated as a standard string which may contain spaces. Python should then properly quote the string when sending it to the shell.

    0 讨论(0)
  • 2021-01-07 18:50

    2 things

    1)

    You probably don't want to use Pipe If the output of the subprogram is greater than 64KB it is likely your process will crash. http://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/

    2) Subprocess.Popen has a keyword argument shell, making it as if the shell has been parsing your arguments, setting shell=True should do what you want.

    0 讨论(0)
提交回复
热议问题