我需要通过Python运行bash shell命令(Debian)并收集输出。
命令是
curl -H "Content-type:application/json" https://api.example.com/api/v1/login -d '{ "ldap": true, "username": "myusername", "ldapPass": "mypassword", "ldapOptions": {} }'
使用正确的URL,用户名和密码替换后,此命令在bash shell中有效。我想使用subprocess.Popen( cmd ...)
在Python程序中运行此命令很明显,在调用Popen(cmd)之前,我必须为 cmd 分配一些东西,但是我不知道是什么。我尝试添加像这样的转义字符:
cmd = "curl -H \"Content-type:application/json\" https://api.example.com/api/v1/login -d '{ \"ldap\": true, \"username\": \"myusername\", \"ldapPass\": \"mypassword\", \"ldapOptions\": {} }'"
p = subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
(child_stderr, child_stdout) = p.communicate()
它没有用,并抛出了一个假胎。
然后我尝试手动构建cmd数组,然后在Popen调用期间不拆分它:
cmd = ["curl","-H","\"Content-type:application/json\"", "https://api.example.com/api/v1/login", "-d","'{ \"ldap\": true, \"username\": \"myusername\", \"ldapPass\": \"mypassword\", \"ldapOptions\": {} }'"]
print(cmd)
print(" ".join(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
(child_stderr, child_stdout) = p.communicate()
这也不起作用,并引发了异常。
有趣的是,当我复制“” .join(cmd)的输出并在shell中运行它时,效果很好。
我用过其他情况,例如
cmd = ["ps", "-ef"]
效果很好。
如何为 cmd (使用单引号和双引号)分配适当的值,以便它可以使用Python的subprocess.Popen()正常运行?