繁体   English   中英

如何在另一个 python 文件中运行 python 文件

[英]How to run python file inside another python file

How do I make this python code containing kivy run in another python code containing kivy like you would call a function so I can have different segment of the code. 我不希望在特定的 python 文件上有太多代码,因为我要处理大代码。

import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label 


class LandingScreen(FloatLayout):
    def __init__(self, **kwargs):
        super(LandingScreen, self).__init__(**kwargs)

         
        self.btn1=Button(text='button1 ', size_hint=(0.5, 0.5), 
        on_press=self.click_b1))
        self.btn2=Button(text='button2', size_hint=(0.5, 0.5), 
        on_press=self.click_b2))


            
        self.add_widget(self.btn1)
        self.add_widget(self.btn2)

        def click_b1(self, instance):
             
             pass
        def click_b2(self, instance):
             pass
       
class SplashApp(App):
    def build(self):
        return LandingScreen()

if __name__ == '__main__':
    SplashApp().run()

我如何在下面的另一个 python 文件中调用这个 python 文件,假设第一个文件是 a.py,第二个文件是 b.py

import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label 


class LandingScreen2(FloatLayout):
    def __init__(self, **kwargs):
        super(LandingScreen2, self).__init__(**kwargs)

         
        self.btn3=Button(text='button1 ', size_hint=(0.5, 0.5), 
        on_press=self.click_b3))
        self.btn4=Button(text='button2', size_hint=(0.5, 0.5), 
        on_press=self.click_b4))


            
        self.add_widget(self.btn3)
        self.add_widget(self.btn4)

        def click_b3(self, instance):
             
             pass
        def click_b4(self, instance):
             pass
       
class SplashApp(App):
    def build(self):
        return LandingScreen2()

if __name__ == '__main__':
    SplashApp().run()

要调用另一个文件,您可以将其视为一个模块,您可以使用:

#a.py
import b
b.execute()
#b.py
def execute() :
    print("This works!")

所有变量和函数都需要有前缀b. 引用示例中的“模块”

这个问题可能与以下问题重复:

https://stackoverflow.com/questions/2349991/how-to-import-other-python-files

它称为import 您可以在当前模块中导入第二个模块,例如b.py并调用该模块的入口点。

a.py

import b
...
...
#call b.py entry point.
b.SplashApp().run()

你可以做一些更普通的事情,产生一个新的进程,并通过 shell 用 python 调用 b.py (但这很特别,我提到这一点只是为了让你知道你可以用 python 做任何你喜欢的事情)

import subprocess
p= subprocess.Popen("python b.py",shell=True)
p.communicate

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM