首页 > 解决方案 > Python3.7,需要帮助 if == ('Nikon'): Nikon is is the verable I and testing

问题描述

下面的简短脚本是我的 rasberry PI 4 上尼康相机控制脚本的一部分,用于控制尼康 D90 的长时间曝光。我调用了一个命令来测试相机是否正在通信,结果在变量 mycmd 中。下面的脚本我只是创建了字符串。但是我的 if 语句总是找不到匹配更少的 Nikon 是 mycmd 中唯一的单词。

import os
import time
import subprocess
import sh
mycmd =("Nikon DSC D90 (PTP mode)       usb:001,008")
if mycmd == ('Nikon'):
    print('gotit')


#mycmd = os.popen('gphoto2 --auto-detect').read()
print(mycmd)
time.sleep(1)
#print(encoded_bytes)
#decoded_string = encoded_bytes.decode('utf-8','replace')
#print(decoded_string)

if mycmd == ('Nikon'):
    print("OK")
else:
    print("error")`
The OUTPUT Below
>> %Run os.popen_example.py
Nikon DSC D90 (PTP Mode)     usb:001,008
error
>>

标签: python-3.x

解决方案


如果“尼康”可能不是第一个词,试试这个:

mycmd = os.popen('gphoto2 --auto-detect').read()
print(mycmd)
time.sleep(1)

if 'Nikon' in mycmd:
    print("OK")
else:
    print("error")

否则,如果您希望“Nikon”始终是第一个标记,请尝试以下操作:

mycmd = os.popen('gphoto2 --auto-detect').read()
print(mycmd)
time.sleep(1)

if mycmd.startswith('Nikon'):
    print("OK")
else:
    print("error")`

推荐阅读