简体   繁体   English

Python 3:使用子进程通过gphoto2拍照,但是无法设置自定义文件名。

[英]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. 当我通过终端进行操作时,一切正常,但是当我使用python脚本时,一切都没有。

Command: gphoto2 --capture-image-and-download --filename test2.jpg 命令: 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. 但是,当我尝试通过python脚本和子进程来执行此操作时,没有任何反应。 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. 虽然我仅使用--capture-image-and-download它可以正常工作,但是却得到了我不想使用的文件名。 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). 如果shell=False ,则需要自己在shlex分割标记(并且最好了解shell如何处理引号;或使用shlex为您完成工作)。

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() ). 除非您坚持使用真正的supbrocess.Popen() Python版本,否则应避免使用supbrocess.Popen() ,而supbrocess.Popen() subprocess.run() (或者对于稍旧的Python版本,则使用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. 较低级别的Popen()接口比较笨拙,但是当较高级别的API无法满足您的要求时,它会为您提供低级别的访问控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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