【问题标题】:Write to the console or to file python写入控制台或文件 python
【发布时间】:2013-07-29 18:06:57
【问题描述】:

我有一个函数:

def hello_world(output):
    output.write("Hello World")

并想将这些传递给它:

file = io.open("myfile.txt", "w")
hello_world(file)
hello_world(sys.stdout)

我不知道这样是否正确。我也得到NameError: global name 'sys' is not defined 你会怎么做我想做的事?

【问题讨论】:

    标签: python file-io io console


    【解决方案1】:

    尝试添加:

    import sys
    

    到文件的顶部

    【讨论】:

      【解决方案2】:

      NameError:未定义全局名称“sys”

      由 Python 文件顶部的 import sys 修复

      顺便说一句,it's a horrible idea to have variables named file or list or dict or pretty much any default type

      【讨论】:

        【解决方案3】:

        您应该在脚本的开头添加这一行:

        import sys
        

        【讨论】:

          【解决方案4】:

          需要导入sys模块:

          import sys
          

          之后你就可以使用sys.stdout了。

          【讨论】:

            【解决方案5】:

            你忘了import sys

            sys是python的“系统特定参数和函数”模块-python docs

            这样做的目的是获取系统特定的标准输出管道,以便 python 文件输出 。就像在流中它可以写入:)。

            文件和sys.stdoutsys.stdinsys.stderr 都只是要写入的流。

            一般来说,如果它显示NameError,您要么忘记导入某些内容,要么没有正确定义某些内容:)

            您可能想将其重写为 opens_file 或类似名称,File 和其他一些类似的词(例如,如果您这样做了 random = 3 则永远不好解决,因为它们被用作各种 Python 对象或内部结构的名称 - 而您即使 Python 应该巧妙地解决这些问题,也要确保没有冲突 :)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-02-14
              • 2017-08-27
              • 1970-01-01
              • 2014-07-06
              • 1970-01-01
              • 1970-01-01
              • 2017-09-30
              • 2020-04-10
              相关资源
              最近更新 更多