如何从另一个脚本调用一个脚本?

2024-11-27 10:42:00
admin
原创
152
摘要:问题描述:我有一个名为的脚本,test1.py它不在模块中。它只包含脚本本身运行时应执行的代码。没有函数、类、方法等。我有另一个作为服务运行的脚本。我想test1.py从作为服务运行的脚本中调用。例如:文件test1.py:print "I am a test" print "s...

问题描述:

我有一个名为的脚本,test1.py它不在模块中。它只包含脚本本身运行时应执行的代码。没有函数、类、方法等。我有另一个作为服务运行的脚本。我想test1.py从作为服务运行的脚本中调用。

例如:

文件test1.py

print "I am a test"
print "see! I do nothing productive."

文件service.py

# Lots of stuff here
test1.py # do whatever is in test1.py

解决方案 1:

通常的做法如下。

测试1.py

def some_func():
    print 'in test 1, unproductive'

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

服务.py

import test1

def service_func():
    print 'service func'

if __name__ == '__main__':
    # service.py executed as script
    # do something
    service_func()
    test1.some_func()

解决方案 2:

在 Python 2 中可以使用以下方法实现execfile

execfile("test2.py")

在 Python 3 中,可以使用以下方法实现exec

exec(open("test2.py").read())

如果对于您的情况来说很重要,请参阅有关命名空间处理的文档。

但是,您应该考虑使用不同的方法;您的想法(从我所看到的)看起来不太清晰。

解决方案 3:

另一种方法:

文件test1.py:

print "test1.py"

文件service.py:

import subprocess

subprocess.call("test1.py", shell=True)

这种方法的优点是您不必编辑现有的 Python 脚本即可将其所有代码放入子例程中。

文档:Python 2、Python 3

解决方案 4:

import os

os.system("python myOtherScript.py arg1 arg2 arg3")  

使用 os,您可以直接调用终端。如果您想要更具体,您可以将输入字符串与局部变量连接起来,即。

command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)

解决方案 5:

我更喜欢runpy:

#!/usr/bin/env python
# coding: utf-8

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

解决方案 6:

如果您希望 test1.py 保持可执行状态,并具有与在 service.py 内部调用时相同的功能,请执行以下操作:

测试1.py

def main():
    print "I am a test"
    print "see! I do nothing productive."

if __name__ == "__main__":
    main()

服务.py

import test1
# lots of stuff here
test1.main() # do whatever is in test1.py

解决方案 7:

你不应该这样做。相反,你应该这样做:

测试1.py:

 def print_test():
      print "I am a test"
      print "see! I do nothing productive."

服务.py

#near the top
from test1 import print_test
#lots of stuff here
print_test()

解决方案 8:

第一次使用时使用import test1- 它将执行脚本。对于后续调用,将脚本视为导入的模块,并调用该reload(test1)方法。

何时reload(module)执行:

  • Python 模块的代码被重新编译,模块级代码被重新执行,定义一组新的对象,这些对象与模块字典中的名称绑定在一起。扩展模块的 init 函数不会被调用

可以使用简单的检查sys.modules来调用适当的操作。要继续将脚本名称引用为字符串 ( 'test1'),请使用内置的“ import ()”。

import sys
if sys.modules.has_key['test1']:
    reload(sys.modules['test1'])
else:
    __import__('test1')

解决方案 9:

为什么不直接导入 test1?每个 python 脚本都是一个模块。更好的方法是在 test1.py 中有一个函数(例如 main/run),导入 test1 并运行 test1.main()。或者您可以将 test1.py 作为子进程执行。

解决方案 10:

正如前面提到的,runpy这是一种从当前脚本运行其他脚本或模块的好方法。

顺便说一句,跟踪器或调试器这样做很常见,在这种情况下,直接导入文件或在子进程中运行文件等方法通常不起作用。

exec使用运行代码时也需要注意。您必须提供适当的信息run_globals以避免导入错误或其他问题。runpy._run_code有关详细信息,请参阅。

解决方案 11:

将其添加到你的python脚本中。

import os
os.system("exec /path/to/another/script")

这将执行该命令,就像它被输入到 shell 中一样。

解决方案 12:

使用子进程执行此操作的一个例子。

from subprocess import run
import sys 
run([sys.executable, 'fullpathofyourfile.py'])

解决方案 13:

这是一个subprocess带库的示例:

import subprocess

python_version = '3'
path_to_run = './'
py_name = '__main__.py'

# args = [f"python{python_version}", f"{path_to_run}{py_name}"]  # works 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_)

解决方案 14:

我发现runpy标准库最方便。为什么?你必须考虑test1.py脚本中出现错误的情况,并且runpy你可以在service.py代码中处理这种情况。回溯文本(将错误写入日志文件以供将来调查)和错误对象(根据错误类型处理错误):当使用subprocess库时,我无法将错误对象从test1.py提升到service.py,只能回溯输出。此外,与“将 test1.py 作为模块导入”解决方案相比,runpy更好,因为你不需要将代码包装test1.pydef main():函数中。

以一段代码为例,使用traceback模块来捕获最后的错误文本:

import traceback
import runpy #https://www.tutorialspoint.com/locating-and-executing-python-modules-runpy

from datetime import datetime


try:
    runpy.run_path("./E4P_PPP_2.py")
except Exception as e:
    print("Error occurred during execution at " + str(datetime.now().date()) + " {}".format(datetime.now().time()))
    print(traceback.format_exc())
    print(e)

解决方案 15:

这个过程有点非正统,但适用于所有 Python 版本,

假设你想在 if 条件中执行名为“recommend.py”的脚本,那么使用,

if condition:
       import recommend

虽然技术不同,但有效!

解决方案 16:

根据给出的例子,这是最好的方法:

# test1.py

def foo():
    print("hellow")
# test2.py
from test1 import foo # might be different if in different folder.
foo()

但根据标题,使用os.startfile("path")是最好的方法,因为它很小而且有效。这将执行指定的文件。我的python版本是3.x +。

解决方案 17:

当我在python 3中搜索解决方案时,我发现了这一点。在 python 3 中,您只需使用import函数即可(请注意,py.files 不应该具有与库相同的名称,它应该具有唯一的名称):

文件test1.py:

print "I am a test"
print "see! I do nothing productive."

文件service.py:

import test1

如果你只运行service.py它将生成输出:

"I am a test" 
"see! I do nothing productive."

请注意,它应该位于同一个存储库/文件夹中。

相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1247  
  IPD(Integrated Product Development)研发管理体系作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用,助力企业提升产品开发效率、降低成本、增强市场竞争力。深入理解其核心要素,对于企业成功实施 IPD 研发管理体系至关重要。以下将对 IPD 研发管理体系的四大核心要素进行详细解析。...
IPD流程中的charter   19  
  IPD(Integrated Product Development)研发管理体系强调将产品开发视为一个完整的流程,从市场需求出发,整合企业的各种资源,实现产品的快速、高质量交付。在这个过程中,成本控制是至关重要的一环,它直接关系到产品的竞争力和企业的盈利能力。有效的成本控制能够确保在不牺牲产品质量和性能的前提下,降低...
IPD开发流程管理   22  
  IPD(Integrated Product Development)项目管理作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用。它通过整合跨部门团队,实现从概念到产品上市的全流程高效管理,提升产品竞争力。深入探讨IPD项目管理的六个关键阶段,对于企业理解和运用这一模式,优化产品开发流程具有重要意义。概念阶段概...
IPD概念阶段   29  
  IPD(Integrated Product Development)流程管理作为一种先进的产品开发管理模式,旨在通过整合各种资源,实现产品开发的高效、协同与创新。在这一流程管理体系下,产品质量保障成为企业关注的核心要点之一。有效的产品质量保障策略不仅能够提升产品的市场竞争力,还能为企业赢得良好的声誉和客户忠诚度。接下...
华为IPD   24  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用