如何在python文件中执行所有代码?

tyl*_*ART 0 python import file

如何在python文件中执行所有代码,以便在当前代码中使用def?我有大约100个脚本,它们都像下面的脚本一样编写.

举个简单的例子,我有一个名为的python文件:

d:/bt_test.py

他的代码看起来像这样:

def bt_test():
    test = 2;
    test += addFive(test)
    return(test)

def addFive(test):
    return(test+5)
Run Code Online (Sandbox Code Playgroud)

现在,我想从一个全新的文件,运行bt_test()

我试过这样做:

def openPyFile(script):
    execfile(script)

openPyFile('D:/bt_test.py')
bt_test()
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

我也尝试过这样做:

sys.path.append('D:/')
def openPyFile(script):
    name = script.split('/')[-1].split('.')[0]
    command = 'from  ' + name +  ' import *'
    exec command

openPyFile('D:/bt_test.py')
bt_test()
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么这不起作用?

这是一个快速视频的链接,可以帮助解释正在发生的事情. https://dl.dropbox.com/u/1612489/pythonHelp.mp4

Ned*_*der 10

您应该将这些文件放在Python路径上的某个位置,然后导入它们.这就是import声明的用途.BTW:与你的主程序在Python路径上的目录相同,这可能是放置它们的好地方.

# Find and execute bt_test.py, and make a module object of it.
import bt_test

# Use the bt_test function in the bt_test module.
bt_test.bt_test()
Run Code Online (Sandbox Code Playgroud)