接收我从第一个Python脚本调用的第二个Python脚本的输出

2024-06-16 10:47:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图寻找一个答案之前,我把它张贴,但我有麻烦的措辞。所以,如果网站上有重复的问题,我道歉。你知道吗

我有一个python脚本(在本例中我们称之为script1),它从另一个脚本(我们称之为script2)调用函数。我是这样做的:

import Script2
Script2.Some_Function()

有些函数执行各种操作,例如连接到internet上的服务器和执行文件查找。通常,如果其中一个任务失败,它会在屏幕上打印一个错误:

def Some_Function():
   def error(err):
     print "Error: " + err

但是,当我知道应该打印一个错误时,我没有看到任何东西被打印到屏幕上。我怀疑这是因为我是从剧本一开始的。 有什么我能做的吗?我真的需要从脚本2输出打印。你知道吗


Tags: 答案脚本屏幕网站def错误functionsome
1条回答
网友
1楼 · 发布于 2024-06-16 10:47:17

如果您的代码与代码片段完全相同,则不太可能正常工作,但首先,让我们使用正确的措辞,在python中,您使用术语module来命名另一个python文件,其中包含要导入当前(module)文件的符号。你知道吗

脚本通常是从命令行界面运行的高级语言中的一小段代码。因此,根据经验,python中的脚本就是放置if __name__ == '__main__':

所以我要重新命名你的例子:

myscript.py文件

import external_module
external_module.some_function()

外部\u模块

def some_function():
   def error(err):
       print "Error: " + err

However, when I know an error should be being printed, I'm not seeing anything being printed to the screen. I suspect this is because I'm calling it from Script 1. Is there anything I can do? I really need the output from Script 2 to be printed.

现在代码被“清理”了一点,当你运行你的程序时发生了什么?你知道吗

python myscript.py

好吧,没什么,这是意料之中的:因为你什么也没做!让我们添加评论:

myscript.py文件

import external_module            # you import the module external_module
external_module.some_function()   # you run the function some_function()
                                  # from external_module

在myscript中没有任何错误。但你的问题出在外部模块上:

外部\u模块

def some_function():              # you declare the function some_function
   def error(err):                # you declare the function error 
                                  # that lives only in some_function() scope
       print "Error: " + err      # in error() you print something out!

因此,当您执行external_module.some_function()时,您只需声明函数error(),而从不运行它,这意味着您从不运行print语句。如果您忘记了import方面,并且只在python REPL中这样做:

>>> def foo():
...    def bar():
...        print("Hello world?")
...
>>> foo()
>>>

它什么都没做!但如果你这么做了:

>>> def foo():
...    def bar():
...        print("Hello World!")
...    bar()            # here you call the function bar() inside foo()
...
>>> foo()
Hello World!
>>>

你可以跑bar()!你知道吗

我希望我的解释足够详尽!你知道吗

HTH公司

相关问题 更多 >