如何从变量调用和运行另一个Python文件
我使用的是Python版本:2.6.6。我在目录:/home/admin中有一个Python代码test2.py 我正在尝试从内部运行该文件:/home/admin/Practice/test.py My test.py代码包含:如何从变量调用和运行另一个Python文件,python,Python,我使用的是Python版本:2.6.6。我在目录:/home/admin中有一个Python代码test2.py 我正在尝试从内部运行该文件:/home/admin/Practice/test.py My test.py代码包含: import os filedir = os.path.realpath(__file__) scriptdir = os.path.dirname(filedir) print (filedir) print (scriptdir) newfile = script
import os
filedir = os.path.realpath(__file__)
scriptdir = os.path.dirname(filedir)
print (filedir)
print (scriptdir)
newfile = scriptdir + "/../" + "test2.py"
new_module = __import__(newfile)
exec("python new_module 100 10"
现在我知道这可能不是从另一个平台运行Python脚本的正确方法。但当我运行这个时,我得到:
[admin@centos1 Practice]$ python test.py
/home/admin/Practice/test.py
/home/admin/Practice
Traceback (most recent call last):
File "test.py", line 7, in <module>
new_module = __import__(newfile)
ImportError: Import by filename is not supported.
[admin@centos1练习]$python test.py
/home/admin/Practice/test.py
/家庭/行政/实践
回溯(最近一次呼叫最后一次):
文件“test.py”,第7行,在
新建模块=\uuuuuu导入(新文件)
ImportError:不支持按文件名导入。
我们必须运行Python脚本:/home/admin/test2.py,它位于变量newfile inside test.py中
有人能告诉我怎么做吗
感谢您的学习。您可以使用内置函数运行另一个Python文件的内容。也就是说,
execfile(filename)
执行当前范围内由filename
指向的文件中的语句 我不建议使用execfile
。事实上,您只需要学习导入如何在Python中工作,您正在学习Python,对吗
你有几种方法来处理这个问题
最简单的方法是将所有内容打包到单个模块中,比如说mytest
mytest
mytest/\uuuu init\uuuu.py
()mytest/test.py
,mytest/test2.py
(您也应该更改名称,但这不是重点。)mytest/test.py
中,只需执行importtest2
,即可执行test2
中的所有代码test2.py
,如:
def foo():
# your code here
因此,在test.py
中,您可以执行以下操作:
import test2
test2.foo()
因此,假设
test2.py
中的代码是:
print "Hello world!"
我的建议将产生如下结果:
文件mytests/\uuuu init\uuuu.py
empty
文件mytest/test.py
:
import test2
test2.my_function_name()
def my_function_name():
print "Hello world!"
文件mytest/test2.py
:
import test2
test2.my_function_name()
def my_function_name():
print "Hello world!"
您可以使用:python mytest/test.py
最后一件事,如果您将文件
test.py
用作命令行入口点(),则应将其重命名为\uuu main\uuuu.py
。您是否尝试使用以下行:newfile=scriptdir+“/…”+“test2”execfile
。