简体   繁体   English

Python:从父脚本运行多个脚本,您还可以在其中设置变量值

[英]Python: run multiple scripts from a parent script where you can also set the variable values

I have a few Python files that I want to execute sequentially in order to get an output and now would like to automate this process.我有几个 Python 文件,我想按顺序执行以获得 output,现在想自动化这个过程。 So I would like to have a parent script from which I can execute all my child scrips in the right order.所以我想要一个父脚本,我可以从中以正确的顺序执行我所有的子脚本。 Also, I would like to execute one of the files twice but with two different date variables and would like to store the outputs in two different folders.另外,我想使用两个不同的日期变量执行其中一个文件两次,并希望将输出存储在两个不同的文件夹中。 How do I create such a parent script in Python?如何在 Python 中创建这样的父脚本?

For example I want to execute file1.py first and the date (a variable in file1.py ) should be date1 and the output should be stored in dir1 and then I want to execute file1.py again but this time the date should be date2 and the output should be in dir2 .例如,我想先执行file1.py并且日期( file1.py中的变量)应该是date1并且 output 应该存储在dir1中,然后我想再次执行file1.py但这次日期应该是date2并且 output 应该在dir2中。 And the I want to execute file2.py .我想执行file2.py How would I do this?我该怎么做?

You can easily run python scripts from another python scripts using subprocesses.您可以使用子进程轻松地从另一个 python 脚本运行 python 脚本。 Something like:就像是:

import subprocess
subprocess.Popen("script2.py some_argument")

Problem with using subprocesses - it's quite annoying to get results from it (you can print results from the script and then get them in the parent file, but still).使用子进程的问题 - 从中获取结果非常烦人(您可以从脚本中打印结果,然后在父文件中获取它们,但仍然如此)。

Better solution - save middle results in some database (like simple SQLite file), so you use your main script to initiate child scripts, but get arguments from the database and write child script results to the database too.更好的解决方案 - 将中间结果保存在某些数据库中(如简单的 SQLite 文件),因此您使用主脚本启动子脚本,但从数据库中获取 arguments 并将子脚本结果也写入数据库。 It's quite easy and could solve your problems ( https://docs.python.org/3/library/sqlite3.html ).这很简单,可以解决您的问题( https://docs.python.org/3/library/sqlite3.html )。

For example, to save some variable in the SQLite database, all you need is:例如,要在 SQLite 数据库中保存一些变量,您只需要:

import sqlite3

conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()

# Create table (no need if it was created before)
cursor.execute("""CREATE TABLE example_table
                  (variable_name, variable_value)
               """)
# Save changes
conn.commit()

# Insert data
cursor.execute("""INSERT INTO example_table
                  VALUES ('some_variable', 'some_value')"""

# Save changes
conn.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM