0

everything works fine while I do it via terminal but when I use python script it doesn't.

Command: 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

I'ts all good. But when I try to do it via python script and subprocess nothing happens. I tried to do it like:

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)

and:

import subprocess
test = subprocess.Popen(["gphoto2", "--capture-image-and-download --filename'test2.jpg'"], stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)

While I use only --capture-image-and-download it works fine, but I get filename that I don't want to. Can you tell me what I do wrong?!

4

1 回答 1

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 不能执行您想要的操作时,您可以进行低级别的访问控制。

于 2018-07-25T13:46:28.050 回答