我想從腳本中運行 Pytest 并將輸出保存為字符串。就像是: test_output=pytest.main(['-qq', '-x', test_dir])
print(test_output)這可能嗎?我知道我可以將它寫入一個文件然后讀取該文件,但這似乎不必要地復雜。
2 回答

SMILET
TA貢獻1796條經驗 獲得超4個贊
你可以使用contextlib.redirect_stdout:
import io
from contextlib import redirect_stdout
import pytest
if __name__ == "__main__":
buffer = io.StringIO()
with redirect_stdout(buffer):
pytest.main()
out = buffer.getvalue()
print(out)

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
我認為如果你有一個虛擬環境,你可以在那里設置環境變量。然后你就可以讀寫它們了。但是創建文件可能更容易。
https://www.nylas.com/blog/making-use-of-environment-variables-in-python/
添加回答
舉報
0/150
提交
取消