Send arbitrary number of inputs from python to .exe


p = subprocess.Popen(args = "myprog.exe" + " " +
                     str(input1) + " " +
                     str(input2) + " " +
                     str(input3) + " " +
                     strpoints, stdout = subprocess.PIPE)

      

in the above code, input1, input2 and input3 are integers that are converted to strings. the "strpoints" variable is a list of arbitrary length strings. input1 tells myprog the length of strpoints. of course, when I try to run the above code, I get the following error:

TypeError: Cannot convert object 'list' to str implicitly

how to pass all strpoints elements to myprog.exe? am I doomed to have to execute str (strpoints) and then myprog.exe parse that for commas, apostrophes, etc.? eg.

`โ†’> x = ['a', 'b']

`โ†’> str (x)

"['a', 'b']"

or should I create a huge string beforehand? eg.

'โ†’> x = [' a ',' b ']

'โ†’> stringify (x)

'ab'

where stringify would be something like


def stringify(strlist):
    rlist = ""
    for i in strlist:
        rlist = rlist + i + " "
    return rlist

      

+2


source to share


4 answers


Try using string.join:



p = subprocess.Popen(args = "myprog.exe" + " " +
                     str(input1) + " " +
                     str(input2) + " " +
                     str(input3) + " " +
                     " ".join(strpoints), stdout = subprocess.PIPE)

      

+4


source


args can be a sequence:

p = subprocess.Popen(args = ["myprog.exe"] + 
                            [str(x) for x in [input1,input2,input3]] + 
                            strpoints,stdout = subprocess.PIPE)

      



This is more correct if your arguments contain shell metacharacters, eg. '* and you don't want them to be interpreted as such.

+7


source


Avoid concatenating all arguments into one string using this string.

It's much easier, better, and safer to just pass a sequence (list or tuple) of arguments. This is especially true if any argument contains a whitespace character (which is quite common for filenames).

+1


source


Any thought you might want to enclose these strings in quotes if they have embedded spaces? Something like:

if strpoints:
    finalargs = '"' + '" "'.join(strpoints) + '"'
else:
    finalargs = ""
p = subprocess.Popen(args = "myprog.exe" + " " +
                 str(input1) + " " +
                 str(input2) + " " +
                 str(input3) + " " +
                 finalargs, stdout = subprocess.PIPE)

      

This makes your string longer, but preserves the integrity of your individual items in the list.

0


source







All Articles