简体   繁体   中英

Python 3: Using subprocess to take photo via gphoto2 but can't set custom filename doing it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM