how to run a file from another python file

吃可爱长大的小学妹 提交于 2019-12-05 08:04:46

问题


a.py

from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.lang import Builder


class CustDrop(DropDown):
    def __init__(self, **kwargs):
        super(CustDrop, self).__init__( **kwargs)
        self.select('')


kv_str = Builder.load_string('''


BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        canvas.before:
            Rectangle:
                pos: self.pos
                size: self.size
            Color:
                rgb: (1,1,1)
        size_hint_y:1

        Button:
            id: btn
            text: 'test'
            on_release: dropdown.open(self)
            #size_hint_y: None
            #height: '48dp'  


        CustDrop:

            id: dropdown

            Button:
                text: 'Run another script'
                size_hint_y: None
                height: '48dp'

        Label:
            size_hint_x: 4

    Label:
        size_hint_y: 9

''')


class ExampleApp(App):
    def build(self):
        return kv_str

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

b.py

import kivy
kivy.require('1.0.6') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):

    def build(self):
        return Label(text='Hello world')


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

when i run a.py file after that i click on test then dropdown show 'run another script'.when i click on 'run another script'(sub menu of test) then how to run b.py(MyApp().run()).It should be print 'Hello world' in new window.


回答1:


The solution is as follow:

Snippet

a.py

...

kv_str = Builder.load_string('''
#:import os os
...
        CustDrop:

            id: dropdown

            Button:
                text: 'Run another script'
                size_hint_y: None
                height: '48dp'
                on_release: os.system("python3 b.py")

Output




回答2:


instead of calling to system, there is a python module to do that

https://docs.python.org/3/library/runpy.html



来源:https://stackoverflow.com/questions/47111074/how-to-run-a-file-from-another-python-file

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