运行 tf.app.run() 时抛出异常

Exception thrown when running tf.app.run()

我现在正在摆弄标志,在使用 tf.app.run() 时遇到了一些奇怪的行为。下面的代码片段应该简单地打印通过命令行给出的字符串。

import tensorflow as tf

# command line flags
tf.app.flags.DEFINE_string('mystring', 'Hello World!',
                           '''String to print to console.''')

FLAGS = tf.app.flags.FLAGS


def main():

    print(FLAGS.mystring)

if __name__ == '__main__':
    tf.app.run()

在执行过程中,抛出了这个错误:

Traceback (most recent call last):

File "", line 1, in runfile('/path/flags.py', wdir='/path')

File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile execfile(filename, namespace)

File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "/path/flags.py", line 19, in tf.app.run()

File "/home/abc/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 126, in run _sys.exit(main(argv))

TypeError: main() takes 0 positional arguments but 1 was given

...这很奇怪,因为我没有给 main() 一个参数。但是,如果我添加下划线 def main(_):,它可以正常工作。

我找不到描述下划线用法的文档。有人知道这里发生了什么吗?谢谢!

当我执行你的代码时,我在 Pycharm IDE 中看到的错误消息更加清晰。

Traceback (most recent call last):
  File "D:/PycharmProjects/TensorFlow/self.py", line 30, in <module>
    tf.app.run()
  File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", 
line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
TypeError: main() takes 0 positional arguments but 1 was given

_sys.exit(main(_sys.argv[:1] + flags_passthrough)) 试图用一个参数调用我们的 main 方法。

这是运行方法app.py

可以使用 运行 方法的简化版本进行测试。

import tensorflow as tf
import sys as _sys
from tensorflow.python.platform import flags


# command line flags
tf.app.flags.DEFINE_string('mystring', 'Hello World!',
                           '''String to print to console.''')

FLAGS = tf.app.flags.FLAGS

def run(main=None, argv=None):
  """Runs the program with an optional 'main' function and 'argv' list."""
  f = flags.FLAGS

  # Extract the args from the optional `argv` list.
  args = argv[1:] if argv else None

  # Parse the known flags from that list, or from the command
  # line otherwise.
  # pylint: disable=protected-access
  flags_passthrough = f._parse_flags(args=args)
  # pylint: enable=protected-access

  main = main or _sys.modules['__main__'].main

  print (_sys.argv[:1])

  # Call the main function, passing through any arguments
  # to the final program.
  #_sys.exit(main(_sys.argv[:1] + flags_passthrough))

  # Call the main function with no arguments
  #_sys.exit(main())


def main():
    print(FLAGS.mystring)

if __name__ == '__main__':
    #tf.app.run()
    run()

print(_sys.argv[1:]) 打印 ['D:/PycharmProjects/TensorFlow/self.py'] 因为 argv[0] 是传递给解释器的脚本名称。

也许你可以从这个link中找到答案,解释app.py如何运行how app.py runs

您还可以使用 def main(argv=None): ... 定义您的主函数,或者像您所做的那样 def main(_): ...,这样它可以为您提供主函数参数。

我在使用 cProfile 和使用

调用脚本时遇到了类似的问题
python -m cProfile train.py

问题似乎是 tf.app.run 在 cProfile 中调用了 main,它还没有准备好传递参数。在我的例子中,解决方案是在 tf.app.run():

中指定 main
tf.app.run(main=main)

不要忘记像这样在 main 中添加假参数 def main(_):