Python: with open 第二次不读任何东西
Python: with open does not read anything the second time
我想记录pip show
命令的return,并识别包的版本(例如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
,我洗耳恭听。
由于您使用的是 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()
我想记录pip show
命令的return,并识别包的版本(例如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
,我洗耳恭听。
由于您使用的是 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()