我正在运行 Ubuntu 14.04 LTS,我有一组 Python 脚本,其中:
- 第一个脚本获取键盘输入,对其进行修改,并将修改后的输出存储在文件中
- 第二个脚本读取第一个脚本生成的输出并获取(额外的)键盘输入,执行操作,并将一些结果存储在第二个文件中
- 等等
为了具体起见,假设我有两个 Python 脚本 1_script.py 和 2_script.py,其源代码如下(在本文末尾)发布)。
我想知道如何在执行以下所有操作的终端中运行单个命令:
- 执行1_script.py
- 在 1_script.py 要求键盘输入时提供“hello”
- 执行 2_script.py
- 提供'!'当 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
第三个脚本 主文件.py
from 1_script import get_input
from 2_script import post_input
if __name__=='__main__':
get_input()
post_input()
print "success"
关于python - 如何自动执行几个相互依赖的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31340998/