https://www.sharetechnote.com/html/Python_CallingPythonScript.htmlhttps://www.sharetechnote.com/html/Python_CallingPythonScript.html
Python - 从另一个脚本调用Python脚本
从另一个脚本调用Python脚本是一种常见的方式,用于模块化代码、重用功能和改善代码组织。这可以通过从一个脚本中导入函数、类或变量到另一个脚本中来实现。当你导入一个脚本时,其中的代码会被执行,并且在调用脚本中可以使用脚本中定义的对象。
以下是调用Python脚本的步骤的高级概述:
组织你的脚本:确保脚本位于同一个目录中,或者在Python导入搜索路径(sys.path)中列出的目录中。这样可以确保Python能够找到要导入的脚本。
在要调用的脚本中定义函数、类或变量:在你想要调用的脚本中,定义你想要在调用脚本中使用的函数、类或变量。这些对象应该在脚本的顶层定义(在任何函数或类的外部),这样在导入脚本时可以访问它们。
示例
你可以从你的脚本中调用(运行)另一个Python脚本。这样,你可以在多个不同的
Python脚本文件中实现各种功能,并将这些功能组合起来。RunScript.py --------------------------------
import os
print("Running the script : test.py....\n")
os.system('python test.py')
test.py --------------------------------
print('Hello World')
You can run the script and get the result as shown below.
Example 02 >
If you have difficulties in understanding RunScript.py due to sys.system(), see Python in Python :Calling Another Script
RunScript.py --------------------------------
import os
import sys
print("Running the script : ", sys.argv[1], "....\n")
os.system('python ' + sys.argv[1])
test.py --------------------------------
print('Hello World')

被折叠的 条评论
为什么被折叠?



