如何自动执行几个相互依赖的 Python 脚本

How to automate the execution of several inter-dependent Python scripts

我正在 运行ning Ubuntu 14.04 LTS,我有一组 Python 脚本,其中:

为了具体起见,假设我有两个 Python 脚本 1_script.py2_script.py,其源码如下(本post末尾)。

我想知道如何在终端中 运行 执行以下所有操作的单个命令:

  1. 执行1_script.py
  2. 1_script.py要求键盘输入
  3. 时提供'hello'
  4. 执行2_script.py
  5. 提供“!”当 2_script.py 要求键盘输入时

如果您能就此提出任何建议,我将不胜感激。

1_script.py

"""
This script:
    1) prompts the user to enter a string
    2) performs modifications to the entered string
    3) stores the modified string into a file 
"""

# get user input
user_entry = raw_input('Enter a string: ')

# perform modifications to the input
modified_data = user_entry + '...'

# store the modified input into a file
f = open('output_from_1_script.txt', 'w')
f.write(modified_data)
f.close()

2_script.py

"""
Dependencies:
    1) before executing this script, the script 1_script.py
        has to have been successfully run

This script:
    1) reads the output generated by 1_script.py
    2) modifies the read data with a user-supplied input
    3) prints the modified data to the screen
"""

# reads the output generated by 1_script.py
f = open('output_from_1_script.txt', 'r')
pregenerated_data = f.readline()
f.close()

# modifies the read data with a user-supplied input
user_input = raw_input('Enter an input with which to modify the output generated by 1_script.py: ')
modified_data = pregenerated_data + user_input

print modified_data

创建一个可以存储所有文件的目录 您可以使用模块系统或将每个函数包含到同一个文件中 进入目录执行下面定义的mainfile.py

1_script.py

"""
This script:
    1) prompts the user to enter a string
    2) performs modifications to the entered string
    3) stores the modified string into a file 
"""
def get_input():
    # get user input
    user_entry = raw_input('Enter a string: ')

    # perform modifications to the input
    modified_data = user_entry + '...'

    # store the modified input into a file
    f = open('output_from_1_script.txt', 'w')
    f.write(modified_data)
    f.close()

下一个脚本将放在下一个文件中

2_script.py

"""
Dependencies:
    1) before executing this script, the script 1_script.py
        has to have been successfully run

This script:
    1) reads the output generated by 1_script.py
    2) modifies the read data with a user-supplied input
    3) prints the modified data to the screen
"""
def post_input():
    # reads the output generated by 1_script.py
    f = open('output_from_1_script.txt', 'r')
    pregenerated_data = f.readline()
    f.close()

    # modifies the read data with a user-supplied input
    user_input = raw_input('Enter an input with which to modify the output     generated by 1_script.py: ')
    modified_data = pregenerated_data + user_input

    print modified_data

第三个脚本 mainfile.py

from 1_script import get_input
from 2_script import post_input

if __name__=='__main__':
    get_input()
    post_input()
    print "success"