简体   繁体   English

Python:如何从脚本中运行脚本?

[英]Python: How to run a script from within a script?

I am starting to learn python and I have made a program that contains a login window. 我开始学习python,并制作了一个包含登录窗口的程序。 Once the user logs in, I want to run a new script with the actual program but I do not want to put that scripts code into the log in windows to keep code organized and neat. 用户登录后,我想使用实际程序运行一个新脚本,但是我不想将该脚本代码放入登录窗口中以保持代码井井有条。 How would I go about doing that? 我将如何去做?

My code in a generic form is this: 我的通用形式的代码是这样的:

from tkinter import *
from re import *
import tkinter.messagebox as box

window = Tk()
window.title( 'Please Login' )
frame = Frame( window )
entry = Entry( frame )
password = Entry( frame , show='*' )
lbl1 = Label( frame , text="Name: " )
lbl2 = Label( frame , text="Alpha Key: " )

pattern = \
compile( 'GENERICPASSWORD' )

def get_passwrd() :
    passwrd = ( password.get() )
    is_valid = pattern.match( passwrd )
    if is_valid :
        # This is where I would like it to run a new script with the actual program.
    else :
        box.showinfo( 'Access Denied' , 'Please Try Again' )

btn = Button( frame , text = 'Log In' , command=get_passwrd )
btn.grid( row=3 , columnspan=2 )
entry.grid( row=1 , column=1 )
password.grid( row=2 , column=1 )
lbl1.grid( row=1 , sticky=E )
lbl2.grid( row=2 , sticky=E )
frame.grid( row=1 , padx=20 , pady=20 )

Use the python package manager. 使用python包管理器。 If your other file was run_this.py and had a main function called main() you would add 如果您的其他文件是run_this.py并具有一个名为main()的主函数,则您将添加

import run_this
run_this.main()

to your script. 到您的脚本。 (generally, the import statement will go at the top of your file, while the call to run_this.main() would go after the login logic.) (通常,import语句将位于文件的顶部,而对run_this.main()的调用将在登录逻辑之后。)

To understand a bit better, when you run a python script it adds the current directory to the python path . 为了更好地理解,当您运行python脚本时,它将当前目录添加到python path中 This path is where python searches for packages and modules. 此路径是python搜索软件包和模块的位置。 A module is a bit of code... a file with a .py ending. 模块是一些代码...以.py结尾的文件。 For my snippet to work, you would have to run your program from the directory containing run_this.py - so that that module would be on your path. 为了使我的代码片段正常工作,您必须从包含run_this.py的目录中运行程序-以便该模块位于您的路径上。

To allow you to better organize your code, you can also use packages- folders full of code. 为了让您更好地组织代码,您还可以使用packages-充满代码的文件夹。 Any folder that conatins a file called __init__.py can be a package. 任何包含名为__init__.py的文件的文件夹都可以是一个包。 Python will check each folder contained within a path folder to see if it is a package, and if so, will make its sub files available. Python将检查path文件夹中包含的每个文件夹,以查看它是否为软件包,如果是,将使其子文件可用。

Say your structure was like this- 假设您的结构是这样的-

parent_folder
    gui.py
    sub_gui.py
    logic
        __init__.py
        run_this.py
        another_file.py

If you ran your application from parent_folder, you could use 如果您从parent_folder运行应用程序,则可以使用

import logic.run_this
import logic.another_file

in gui.py to access their code. 在gui.py中访问其代码。 Futher, from inside run_this.py, you could use 此外,您可以在run_this.py内部使用

import gui
import logic.another_file

this is because gui gets picked up on the python path, while another_file doesn't... but it the package logic does get picked up, and that contains another_file. 这是因为gui在python路径上被拾取,而another_file却没有...但是包逻辑确实被拾取了,并且其中包含another_file。

You will notice that your python interpreter adds a couple things to your PYTHONPATH- inside your python directory are some folders like "site-packages" that get added to the path. 您会注意到,您的python解释器在PYTHONPATH中添加了一些内容-在python目录中,有一些文件夹(例如“ site-packages”)已添加到路径中。 Somewhere in there is a file or packaged named tkinter that you imported at the beginning of this file :) 在该文件的开头导入了一个名为tkinter的文件或打包的文件:

EDIT 编辑

The actual contents of a module get executed when that module gets imported. 导入模块时将执行该模块的实际内容。 Functions and classes get defined, and code that is not contained in anything gets executed. 将定义函数和类,并执行未包含在任何内容中的代码。 Code like 像这样的代码

module A 模块A

a = "world"
print a

Module B 模块B

import A
print "hello"

would output "world hello". 将输出“世界你好”。 Instead, move your logic into a structure like a function- 相反,将您的逻辑移至类似函数的结构中-

module A 模块A

def main():
    a = "world"
    print a

Module B 模块B

import A
print "hello"
A.main()

would output "hello world". 将输出“ hello world”。 Note that main() is defined inside the module, so we refer to it as A.main! 注意main()是在模块内部定义的,因此我们将其称为A.main! We could also import a single identifier from the module- 我们还可以从模块中导入单个标识符-

from A import main

would only import that function (and not any other functions or classes in the file). 只会导入该函数(而不是文件中的任何其他函数或类)。 We could then execute it without referring to the module 然后我们可以执行它而无需参考模块

main() 主要()

  • though in this case, we'd have to be careful not to have something else called main() in our current module! 尽管在这种情况下,我们必须要小心,不要在当前模块中使用其他名为main()的东西! One final trick you will see in python projects is to add 您将在python项目中看到的最后一个技巧是添加

    if name == 'main': main() 如果名称 =='main':main()

which would let you import the code without running it early, but still run that file as a standalone script. 这样一来,您就可以导入代码而无需提前运行它,但仍可以将该文件作为独立脚本运行。

I think you are looking for the subprocess module. 我认为您正在寻找子流程模块。

Here's some information about it: https://docs.python.org/2/library/subprocess.html 这是关于它的一些信息: https : //docs.python.org/2/library/subprocess.html

You can use it like this: 您可以像这样使用它:

import subprocess
subprocess.call(["command", "arguments"])

As you said you started to learn python, you should look for: 正如您所说的,您开始学习python时,应该寻找:

import os
os.system('command')

But Using subprocess module is the better method. 但是使用子过程模块是更好的方法。

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

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