当我执行下面的代码时,它什么也没显示。 操作系统:窗口 8.1 蟒蛇版本:3.7.4
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine("postgresql://postgres:123@127.0.0.1:62621/postgres")
db = scoped_session(sessionmaker(bind=engine))
def main():
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
for flight in flights:
print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")
if __name__ == "__main__":
main()
在此处输入图像描述
你没有执行 main。此块
if __name__ == "__main__":
main()
应该不在主函数
您的缩进在所有代码中都是错误的。尝试这样的事情:
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine("postgresql://postgres:123@127.0.0.1:62621/postgres")
db = scoped_session(sessionmaker(bind=engine))
def main():
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
for flight in flights:
print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")
if __name__ == "__main__":
main()
另外,我鼓励你阅读一些关于Python的缩进文档:https://docs.python.org/3/reference/lexical_analysis.html#indentation