【问题标题】:Python: with open does not read anything the second timePython:第二次打开不读取任何内容
【发布时间】:2016-02-21 19:32:17
【问题描述】:

我想记录pip show 命令的返回,并确定包的版本(例如pytest)。如果存在另一个日志,则应将其覆盖。

所以我决定将pip show 命令写入一个文件,然后以读取模式重新打开它来解析它。如果我没有在for 循环行上放置断点,第二个open 不会读取任何内容。

我使用两个不同的文件名,甚至在实际阅读之前都使用seek(0)...

# checking the installed package version using pip. Writing to file for further use
with open("lib_install.log", "w") as pip_log:
    subprocess.Popen(["pip", "show", "pytest"], stdout=pip_log, stderr=pip_log)

# Lets retrieve the log and parse for the version
current_version = "not installed properly"
with open("lib_install.log", "r") as pip_log_read:
    pip_log_read.seek(0)
    for line in pip_log_read.readlines():
        if "Version: " in line:
            current_version = line.strip("Version: ")
            break

你们有什么想法吗?

顺便说一句,如果你知道我如何在没有Popen 的情况下使用pip,我会全力以赴。

【问题讨论】:

    标签: python python-2.7 pip popen


    【解决方案1】:

    由于您使用的是Popen,因此您的主线程将继续执行,因此它是不确定的,并且可能在 pip 命令完成之前执行。

    with open("lib_install.log", "w") as pip_log:
        subprocess.Popen(["pip", "show", "pytest"], stdout=pip_log, stderr=pip_log)
    
    current_version = "not installed properly" # This will not necessarily be
                                               # executed after the Popen is done.
    

    使用subprocess.call或使用Popen返回对象的wait方法。

    with open("lib_install.log", "w") as pip_log:
        p = subprocess.Popen(["pip", "show", "pytest"], stdout=pip_log, stderr=pip_log)
        p.wait()
    

    【讨论】:

    • 你是对的。它现在正在工作,使用 p.wait()。谢谢你。我认为“打开”结构向您保证文件在离开时已关闭...
    • @joris255:注意:Popen()+wait() 只是subprocess.call()。如果pip 失败,使用subprocess.check_call() 自动引发异常
    • 您的评论不正确current_version 严格在Popen() 之后运行。 Popen() 启动子进程并返回而不等待子进程完成但没有其他线程。
    • 它更像是“当您尝试在主线程中读取它时,pip_log 可能没有被写入子进程中”
    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多