【问题标题】:Is every instance of subprocess.Popen() its own shell?subprocess.Popen() 的每个实例都有自己的外壳吗?
【发布时间】:2021-07-19 10:05:43
【问题描述】:

背景: 我正在尝试制作一个通过 GUI (Tkinter)、Youtube_DL 和 FFmpeg 播放音乐的应用程序。实际应用程序完成后,它还需要 FFmpeg 作为环境变量才能工作。现在,我正在尝试确保创建“个人”FFmpeg 环境变量以使应用程序可移植(最后一步是使用 pyinstaller 制作 .exe 文件)。

问题: 我正在尝试通过 SET 传递 subprocess.Popen 来为 FFmpeg 创建环境变量:

add_ffmpeg = subprocess.Popen(f"IF EXIST {path2set} SET PATH=%PATH%;{path2set}", shell=True)

当我尝试echo %PATH%(使用Popen)时,应该存在的FFmpeg 变量不存在。我只需要知道我是否在 SET 上浪费时间,而应该使用 SETX 或其他解决方案,我很乐意被告知我做错了。

相关代码:

# get any sub-directory with ffmpeg in it's name
ffmpeg = glob(f"./*ffmpeg*/")

# proceed if there is a directory
if len(ffmpeg) > 0:
    # double-check directory exists
    ffmpeg_exist = path.isdir(ffmpeg[0])

    if ffmpeg_exist:
        print("FFmpeg: Found -> Setting Up")
        
        # get the absolute path of the directories bin folder ".\ffmpeg-release-essentials.zip\bin"
        path2set = f"{path.abspath(ffmpeg[0])}\\bin\\"
        
        # add path of directory to environment variables
        add_ffmpeg = subprocess.Popen(f"IF EXIST {path2set} SET PATH=%PATH%;{path2set}", shell=True)
        add_ffmpeg.wait()
        
        # print all of the current environment variables
        list_vars = subprocess.Popen("echo %PATH%", shell=True)
        list_vars.wait()

else:
    print("FFmpeg: Missing -> Wait for Download...")
    
    # download the ffmpeg file via direct link
    wget.download("https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip")
    
    # unzip the file
    powershell = subprocess.Popen("powershell.exe Expand-Archive -Path './ffmpeg-release-essentials.zip' "
                                  "-DestinationPath './'")
    powershell.wait()

    # remove the file
    remove("./ffmpeg-release-essentials.zip")

    # get any sub-directory with ffmpeg in it's name
    ffmpeg = glob("./*ffmpeg*/")

    # double-check directory exists
    ffmpeg_exist = path.isdir(ffmpeg[0])
    
    # proceed with if it exists
    if ffmpeg_exist:
        print("FFmpeg: Found -> Setting Up")
        
        # get the absolute path of the directories bin folder ".\ffmpeg-release-essentials.zip\bin"
        path2set = f"{path.abspath(ffmpeg[0])}\\bin\\"
        
        # add path of directory to environment variables
        add_ffmpeg = subprocess.Popen(f"IF EXIST {path2set} SET PATH=%PATH%;{path2set}", shell=True)
        add_ffmpeg.wait()

        # print all of the current environment variables
        list_vars = subprocess.Popen("echo %PATH%", shell=True)
        list_vars.wait()
        
    else:
        print("Something unexplained has gone wrong.")
        exit(0)

【问题讨论】:

  • 但请记住,所有这些子流程都会继承您的环境。如果您更改 os.environ 以添加或更改变量,您的子流程将会看到。
  • 实际上不需要shell=True 以subprocess.Popen() 开头,首先是cmd.exe 的实例,带有选项/C 和用Python 代码编写的命令行作为附加参数(s )。可以使用完整的限定文件名(驱动器 + 路径 + 名称 + 扩展名)直接运行 ffmpeg.exe,而无需启动 Windows 命令处理器。请仔细完整地阅读subprocess module 的 Python 文档。
  • 模块的描述以及可以传递给subprocess函数的所有参数的描述可以通过阅读Windows内核库函数CreateProcess和结构@的微软文档更好地理解987654323@ 因为subprocess 模块在Windows 上只是CreateProcess 的Python 包装器,不带或带STARTUPINFO 调用。
  • 在发布的代码的第一行中已经有一个更常见的初学者错误。 ffmpeg 目录的搜索是通过相对于当前目录的路径完成的。启动 python.exe 以解释 Python 脚本或稍后创建的可执行文件的当前目录可以是任何目录,因为可执行文件始终可以从使用可执行文件的完整限定文件名的任何目录启动。 sys.executable 应该用于获取处理 Python 脚本的可执行文件的完整路径。最后应该使用那个绝对路径。
  • 另见 How do I get the path and name of the file that is currently executing? os.path.realpath(__file__) 可用于获取当前由 python.exe 在尚未转换为可执行文件的编码 Python 脚本上解释的 Python 脚本文件的绝对路径。如果ffmpeg 始终与Python 脚本或其可执行文件一起安装,则应在os.path.realpath(__file__) 或sys.executable 返回的目录中搜索带有ffmpeg 的目录。

标签: python cmd ffmpeg environment-variables popen


【解决方案1】:

确实,每个子进程都是一个单独的 进程 - 这就是“子进程”的含义 - 这意味着如果您在一个 subprocess 调用中 set 某事,它只会在该子进程中可见,而不是在其父进程或您随后运行的其他子进程中。

一种常见的解决方案是将env 关键字参数传递给subprocess 调用,其中包含您要设置的任何变量;

from pathlib import Path
from os import environ

env = environ.copy()

if Path(path2set).exists():
    env['PATH'] = '%s;%s' % (path2set, env['PATH'])

subprocess.Popen([...], env=env)

当然,在许多情况下,在父进程中执行此修改就足够了,并且任何子进程都继承了新值。 (直接修改os.environment,不要复制,把最后一行的env=env去掉)。

子进程是否是 shell 是一个单独的主题,与您的问题实际上无关。微不足道,shell=True 是;但就像在您的示例中一样,如果您的子流程是例如powershell.exe 那么它就是一个外壳,因为它就是这样(另外shell=True 是相当多余的,可能something you want to avoid if possible).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多