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?!
On the command line, quotes and spaces are consumed by the shell; with shell=False
you need to split up the tokens on whitespace yourself (and ideally understand how the shell processes quotes; or use shlex
to do the work for you).
import subprocess
test = subprocess.Popen([
"gphoto2",
"--capture-image-and-download",
"--filename", "test2.jpg"],
stdout=subprocess.PIPE)
output = test.communicate()[0]
print(output)
Unless you are stuck on a truly paleolithic Python version, you should avoid supbrocess.Popen()
in favor of subprocess.run()
(or, for slightly older Python versions, subprocess.check_output()
). The lower-level Popen()
interface is unwieldy, but gives you low-level access control for when the higher-level API doesn't do what you want.