简体   繁体   English

如何在主脚本中运行另一个脚本

[英]How do I run another script, inside my main script

I don't know how to run another script inside my main Python script. 我不知道如何在我的主Python脚本中运行另一个脚本。 For example: 例如:

Index.py: Index.py:

  Category = "math"
  Print (Category)
  Print ("You can use a calculator")
  Print ("What is 43.5 * 7")
  #run calculator.py
  Answer = int(input("What is your answer"))

How do I run my calculator script inside of this without having to write the calculator code inside of my index script? 如何在其中运行我的计算器脚本而不必在我的索引脚本中编写计算器代码?

Since your other "script" is a python module (.py file) you can import the function you want to run: 由于您的其他“脚本”是python模块(.py文件),您可以导入要运行的函数:

index.py: index.py:

from calculator import multiply  # Import multiply function from calculator.py

category = "math"
print(category)
print("You can use a calculator")
print("What is 43.5 * 7")

#run calculator.py
real_answer = multiply(43.5, 7)

answer = int(input("What is your answer"))

calculator.py calculator.py

def multiply(a, b)
    return a * b

You need to use execfile, and the sintax are available on: https://docs.python.org/2/library/functions.html#execfile . 您需要使用execfile,并且可以在以下网址获得sintax: https//docs.python.org/2/library/functions.html#execfile Example: 例:

execfile("calculator.py")

If you using are Python 3.x, Use this folowing code: 如果您使用的是Python 3.x,请使用以下代码:

with open('calculator.py') as calcFile:
    exec(calcFile.read())

PS: You should consider use the import statement, because is more simple and useful PS:你应该考虑使用import语句,因为它更简单实用

暂无
暂无

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

相关问题 我如何在 django 中运行脚本? - how do i run a Script inside django? 如何在另一个进程/线程中运行模块并使用它的功能而不阻塞主脚本 - How do I run a module in another process/thread and use it's functions without blocking main script 从我的Python脚本内部,我想安排另一个Python脚本或命令行脚本的延迟运行 - From inside my Python script, I want to schedule a deferred run of another Python script or a command line script 在 Python 中,如何同时从主脚本运行另一个 Python 脚本并在停止主脚本时将其关闭? - In Python, how can I run another Python script from the main script at the same time and close it when I stop the main script? 如何在Python中运行bash脚本,但就好像它从另一个目录运行? - How do I run a bash script inside Python, but act as if it's running from another directory? 在PyCharm中运行主代码后自动运行另一个脚本 - Automatically run another script after i run main code in PyCharm 我如何从另一个python脚本运行一个python脚本而又不中断第二个python脚本? - How do i run a python script from another python script without the secondary script interrupting the first? 在python代码中,如何运行.sh脚本? - Inside python code, how do I run a .sh script? 如何在 OBS 中将 python-osc 作为脚本运行? - How do I run python-osc inside OBS as script? 如何从另一个Python脚本内部运行Python脚本? - How to run a Python script from inside of another Python Script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM