首页 > 解决方案 > Python在退出前运行bash脚本

问题描述

我正在尝试用 python 调用一个 bash 脚本,但我需要它是最后执行的。

我想只要在我的脚本末尾添加这个就可以了:

val = subprocess.check_call("/scripts/files.sh '%s'" % title,   shell=True)

但是它在它上面的代码之前被执行,为什么?

上面的最后几行:

print(q_1)
print(q_2)
print(q_3)
cursor.execute(q_1)
cursor.execute(q_2)
cursor.execute(q_3)
mariadb_connection.commit()
cursor.close()
mariadb_connection.close()

如果这很重要,我也会在所有这些代码之前使用val = subprocess.check_call来运行另一个 bash 脚本

我如何确定我的脚本将是最后执行的事情?

标签: bashpython-2.7

解决方案


假设您的脚本看起来像

obj = MySqlSomething()
things
more things
val = subprocess.check_call(x)

如果该类MySqlSomething有一个析构函数,它将在 之后调用check_call,当您从脚本末尾掉出并obj超出范围时。解决方法是让这种情况更早发生,只需将这些东西移动到一个函数中即可:

def main_main():
    obj = MySqlSomething()
    things
    more things

main_main()
val = subprocess.check_call(x)

使用这种安排,obj在结尾处超出范围main_main


推荐阅读