代码之家  ›  专栏  ›  技术社区  ›  Oussama Gamer

使用Python配置分析器将ini中的值更改为空

  •  1
  • Oussama Gamer  · 技术社区  · 1 年前

    如果值为空,我想读取配置文件

    示例:将视频文件转换为音频文件

    config.ini
    [settings]
    videofile = video.avi
    codesplit = -vn
    outputfile = audio.mp3
    

    输出

    ['ffmpeg.exe', '-i', 'video.avi', '-vn', 'audio3.mp3']
    

    如果将值“codesplit”设为空,则代码将无法工作。 示例:将视频avi文件转换为视频mp4

    [settings]
    videofile = video.avi
    codesplit = 
    outputfile = videoaudio.mp4
    

    输出

    ['ffmpeg.exe', '-i', 'video.avi', '', 'videoaudio.mp4']
    

    我想删除这句话,这样代码才能正常工作

     '',
    

    完整代码

    import subprocess
    import configparser
    
    
    config = configparser.ConfigParser(allow_no_value=True)
    config.read(r'config.ini')
    videofile = config.get('settings', 'videofile')
    outputfile = config.get('settings', 'outputfile')
    codesplit = config.get('settings', 'codesplit', fallback=None)
    
    
    
    ffmpeg_path = r"ffmpeg.exe"
    
    
    command = [
        f"{ffmpeg_path}",
        "-i", (videofile),
        (codesplit),
        (outputfile),]
    
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        universal_newlines=True)
    process.communicate()
    
    print(command)
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   ZCGCoder    1 年前

    您可以尝试使用if-else语句来检查是否存在 codesplit 是否从配置文件传递了选项。

    import subprocess
    import configparser
    
    
    config = configparser.ConfigParser(allow_no_value=True)
    config.read(r"config.ini")
    videofile = config.get("settings", "videofile")
    outputfile = config.get("settings", "outputfile")
    codesplit = config.get("settings", "codesplit", fallback=None)
    
    
    ffmpeg_path = r"ffmpeg.exe"
    
    if codesplit:
        command = [
            f"{ffmpeg_path}",
            "-i",
            (videofile),
            (codesplit),
            (outputfile),
        ]
    else:
        command = [
            f"{ffmpeg_path}",
            "-i",
            (videofile),
            (outputfile),
        ]
    
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        universal_newlines=True,
    )
    process.communicate()
    
    print(command)
    

    此代码检查是否 代码分割 配置中有。如果是这样,它会将其添加到 command 列表。如果没有,就没有。

    输出看起来像

    ['ffmpeg.exe', '-i', 'video.avi', 'videoaudio.mp4']
    

    其中不存在空字符串。