当我通过终端执行所有操作时,一切正常,但是当我使用python脚本时却行不通。
命令:
gphoto2 --capture-image-and-download --filename test2.jpg
New file is in location /capt0000.jpg on the camera
Saving file as test2.jpg
Deleting file /capt0000.jpg on the camera
我一切都很好。 但是,当我尝试通过python脚本和子进程来执行此操作时,没有任何反应。我尝试这样做:
import subprocess
text1 = '--capture-image-and-download"'
text2 = '--filename "test2.jpg"'
print(text1 +" "+ text2)
test = subprocess.Popen(["gphoto2", text1, text2], stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)
和:
import subprocess
test = subprocess.Popen(["gphoto2", "--capture-image-and-download --filename'test2.jpg'"], stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)
虽然我仅使用--capture-image-and-download
可以正常工作,但是却得到了我不想使用的文件名。你能告诉我我做错了什么吗?!
答案 0 :(得分:1)
在命令行上,引号和空格被shell占用;使用shell=False
,您需要自己在空白处分割标记(并理想地了解shell如何处理引号;或使用shlex
为您完成工作)。
import subprocess
test = subprocess.Popen([
"gphoto2",
"--capture-image-and-download",
"--filename", "test2.jpg"],
stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)
除非您坚持使用真正的旧石版Python版本,否则应避免使用supbrocess.Popen()
,而推荐使用subprocess.run()
(对于稍旧的Python版本,则应使用subprocess.check_output()
)。较低级别的Popen()
界面比较笨拙,但是当较高级别的API无法满足您的要求时,您可以使用较低级别的访问控制。