how to run a file from another python file

2019-04-02 20:17发布

问题:

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