python subprocess calling bash script - need to print the quotes out too

前端 未结 3 678
你的背包
你的背包 2021-01-19 05:52

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

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

相关标签:
3条回答
  • 2021-01-19 06:18

    I haven't checked why this works, but it does and without the need for shell=True.

    subprocess.Popen(["/bin/bash", "myscript.sh", '""' + string_to_be_quoted + '""', path_to_files])
    
    0 讨论(0)
  • 2021-01-19 06:20

    That's a list, those are strings in it, so they need quotes:

    ["myscript.sh", "var=11; ignore all", "/path/to/files"]
    

    That should work. If your script really somehow relies on quotes, then try this (I don't know the details of how subprocess works):

    ["myscript.sh", "'var=11; ignore all'", "/path/to/files"]
    
    0 讨论(0)
  • 2021-01-19 06:33

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

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

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

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

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