Calling app from subprocess.call with arguments

后端 未结 1 1312
终归单人心
终归单人心 2020-12-09 08:27

I\'m a beginner in Python, and I\'ve been trying to call a command line app, but it fails:

>>> import subprocess as s
>>> s.call(\"gpio -g          


        
相关标签:
1条回答
  • 2020-12-09 08:29

    You're not using call right. Look at the introduction or any of the examples in the docs. The first argument of call is "args", a sequence of arguments, where arg[0] is the program to run.

    So, when you do this:

    s.call("gpio -g read 17")
    

    There are two ways subprocess could interpret this. It should run a program called "g" with arguments "p", "i", "o", " ", etc. (Remember, strings are sequences of characters.) It might instead run a program called "gpio -g read 17" with no additional arguments. Either way, it's not going to find such a program. (Unless you happen to have a program called "g" or "gpio -g read 17" on your PATH, in which case it'll do the wrong thing instead of giving you an error…)

    What you want is:

    s.call(["gpio", "-g", "read", "17"])
    

    So, why does this work if you pass shell=True? Because this whole string gets passed to the shell, which then does its own parsing of the command line and separates things by spaces. It's like calling os.system("gpio -g read 17").

    Please note that all of the above is a bit oversimplified (it ignores Windows, and shell parsing isn't really just "separate by spaces", and so on), so you should actually read the documentation. (Also, whoever wrote the subprocess docs is a better writer than me.)

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