How to run a script within another script?

风格不统一 提交于 2020-01-06 04:51:34

问题


I want to run a script within a script in IDLE. How do I run them?

I have Python 3.8 on Windows 10. I also use Tkinter. Thanks, bye!


回答1:


You basically import the class/function from the other script. For example:

from other_script import a_class

Now, make sure you open your IDLE in the same directory of the other script so you can import it.




回答2:


Another python script can be executed by using runpy module.

Let's say we have two scripts as:

  • abc.py
print('Executing abc.py')
  • main.py
import runpy
runpy.run_path('abc.py') #Path to the abc.py
  • Output
Executing abc.py



回答3:


Do this

import os
os.startfile(file)



回答4:


It depends if you like to get the results of the first script. If not (no output), the easy way:

import os
os.system('full_path_to_the_script')

If you mind the output of the script you are running you can use the following:

import subprocess
p = subprocess.Popen('full_path_to_the_script', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
ret_code = p.returncode

For more information about subprocess.

You can see more examples here.

P.S If the script is located at the same location of the running script I believe that there is no need in full path.



来源:https://stackoverflow.com/questions/59358917/how-to-run-a-script-within-another-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!