Python 从另一个脚本调用脚本的最佳方式是什么?
我有一个名为Python 从另一个脚本调用脚本的最佳方式是什么?,python,Python,我有一个名为test1.py的脚本,它不在模块中。它只有当脚本本身运行时应该执行的代码。没有函数、类、方法等。我有另一个作为服务运行的脚本。我想从作为服务运行的脚本调用test1.py 例如: 文件test1.py: print "I am a test" print "see! I do nothing productive." # Lots of stuff here test1.py # do whatever is in test1.py 文件
test1.py
的脚本,它不在模块中。它只有当脚本本身运行时应该执行的代码。没有函数、类、方法等。我有另一个作为服务运行的脚本。我想从作为服务运行的脚本调用test1.py
例如:
文件test1.py
:
print "I am a test"
print "see! I do nothing productive."
# Lots of stuff here
test1.py # do whatever is in test1.py
文件service.py
:
print "I am a test"
print "see! I do nothing productive."
# Lots of stuff here
test1.py # do whatever is in test1.py
我知道有一种方法是打开文件,读取内容,然后基本上对其进行评估。我想有更好的方法。至少我希望如此。在Python 2中,使用
execfile("test2.py")
有关名称空间的处理,请参阅
在Python3中,这是可以使用的(感谢@fantatory)
但是,你应该考虑使用不同的方法;您的想法(据我所见)看起来不太清晰。为什么不直接导入test1?每个python脚本都是一个模块。更好的方法是在test1.py中使用一个函数,例如main/run,导入test1并运行test1.main()。或者您可以将test1.py作为子流程执行。您不应该这样做。相反,要: test1.py:
def print_test():
print "I am a test"
print "see! I do nothing productive."
service.py
#near the top
from test1 import print_test
#lots of stuff here
print_test()
import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
第一次使用-它将执行脚本。对于以后的调用,将脚本视为导入的模块,并调用该方法
执行重新加载(模块)
时:
- Python模块的代码被重新编译,模块级代码被重新执行,定义了一组绑定到模块字典中名称的新对象。未调用扩展模块的init函数
'test1'
),请使用内置的
如果希望test1.py保持可执行状态,并具有与调用inside service.py时相同的功能,请执行以下操作: test1.py
def main():
print "I am a test"
print "see! I do nothing productive."
if __name__ == "__main__":
main()
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
#near the top
from test1 import print_test
#lots of stuff here
print_test()
import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
通常的方法如下所示 test1.py
def main():
print "I am a test"
print "see! I do nothing productive."
if __name__ == "__main__":
main()
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
#near the top
from test1 import print_test
#lots of stuff here
print_test()
import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
另一种方式:
文件test1.py:
文件服务.py:
这种方法的优点是,不必编辑现有的Python脚本就可以将其所有代码放入子例程中
文件:
使用操作系统,您可以直接呼叫您的终端。如果您想更具体一些,可以将输入字符串与局部变量连接起来,即
command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)
这是
子流程
库的一个示例:
import subprocess
python_version = '3'
path_to_run = './'
py_name = '__main__.py'
# args = [f"python{python_version}", f"{path_to_run}{py_name}"] # Avaible in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()
if not error_:
print(output)
else:
print(error_)
我更喜欢:
如前所述,
runpy
是从当前脚本运行其他脚本或模块的好方法
顺便说一句,跟踪程序或调试器执行此操作非常常见,在这种情况下,直接导入文件或在子流程中运行文件等方法通常不起作用
还需要注意使用
exec
来运行代码。您必须提供适当的run_globals
,以避免导入错误或其他一些问题。有关详细信息,请参阅runpy.\u run\u code
。此过程有点不正统,但适用于所有python版本
假设要在“if”条件内执行名为“recomment.py”的脚本,则使用
if condition:
import recommend
技术是不同的,但工作 将其添加到python脚本中
import os
os.system("exec /path/to/another/script")
这将执行该命令,就像它被键入shell一样。使用子流程执行该命令的示例
从子流程导入运行
导入系统
run([sys.executable,'fullpathofyourfile.py'])
更好的方法是编写方法和类并使用它们:还没有人给出答案?!我在Python32中直接需要的是exec(open('test2.py').read()),这种方法执行调用名称空间中的脚本。:)要将命令行参数传递给脚本,可以编辑sys.argv
list。对Python3等价物进行更全面的处理:这不接受参数(要传递到PY文件)!我必须使用subprocess.call(“./test1.py”,shell=True)
使其工作。除非有必要,否则不要使用shell=True
。它在当前目录不在路径中的典型Unix上不起作用test1.py
应该是可执行的,并且有shebang行(#!/usr/bin/env python
),您应该指定完整路径,或者您需要自己提供可执行文件:call([sys.executable,os.path.join(get_script_dir(),'test1.py'))
where.或者subprocess.call(['python','test1.py'))
@NitishKumarPal No;正如前面的评论中已经指出的,如果可以,您应该避免使用shell=True
。这里没有shell功能,因此subprocess.call(['python','test1.py'])
肯定更好,不过您可能应该使用check\u call
或run
(或者不将python作为python的子进程运行)。在Python中也看到了代码>重载< /代码>。导入一个模块并不等同于运行它,例如,请考虑<代码>,如果y.NAMEYSY= =“YON MNEXYI”:< /代码>守护。可能还有其他更微妙的区别。不要将任意代码留在全局级别。将它放入一个函数中,并在导入后调用它,如instead中所建议的那样如果test1.py
位于某个遥远的目录中怎么办?@evgenisergev看到这并没有真正回答问题,是吗?您不是在执行整个脚本,而是在从您导入的脚本中执行一些函数。@GennaroTedesco:您弄错了。service.py
中的import test1
确实执行了整个脚本(它只定义了一些函数()
,因为在这种情况下\uu name\uuuu=='\uuuu main\uuuu'
将是False
)。这听起来像是OP想要做的。这个答案超出了这个范围,但肯定回答了这个问题?