Python:with open第二次不读取任何内容
我想记录pipshow命令的返回,并识别包pytest的版本。如果存在另一个日志,则应覆盖该日志 所以我决定在一个文件中编写pipshow命令,然后以读取模式重新打开它来解析它。如果我没有在for循环行上放置断点,则第二个open不会读取任何内容 我使用两个不同的文件名,甚至在实际读取之前进行seek0Python:with open第二次不读取任何内容,python,python-2.7,pip,popen,Python,Python 2.7,Pip,Popen,我想记录pipshow命令的返回,并识别包pytest的版本。如果存在另一个日志,则应覆盖该日志 所以我决定在一个文件中编写pipshow命令,然后以读取模式重新打开它来解析它。如果我没有在for循环行上放置断点,则第二个open不会读取任何内容 我使用两个不同的文件名,甚至在实际读取之前进行seek0 # checking the installed package version using pip. Writing to file for further use with open("li
# 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,我洗耳恭听。由于您使用的是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返回对象的方法
with open("lib_install.log", "w") as pip_log:
p = subprocess.Popen(["pip", "show", "pytest"], stdout=pip_log, stderr=pip_log)
p.wait()
因为您使用的是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返回对象的方法
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:note:Popen+wait只是subprocess.call。如果pip失败,请使用subprocess.check_调用自动引发异常您的注释不正确当前_版本严格在Popen之后运行。Popen启动子进程并返回,而不等待子进程完成,但没有其他线程。更重要的是,当您尝试在主线程中读取pip_日志时,可能没有在子进程中写入pip_日志。您是对的。它正在工作,使用p.wait。非常感谢。我认为具有开放结构的文件可以向您保证,在离开文件时文件已关闭…@joris255:note:Popen+wait只是subprocess.call。如果pip失败,请使用subprocess.check_调用自动引发异常您的注释不正确当前_版本严格在Popen之后运行。Popen启动子进程并返回,而不等待子进程完成,但没有其他线程。更重要的是,当您尝试在主线程中读取pip_日志时,可能没有在子进程中写入pip_日志