Tensorflow 测试helloWorld,显示 The session graph is empty

准备学Tensorflow ,win10装好了环境,Anaconda +pycharm+tensorflow,
准备测试简单的hello world程序,结果显示“The session graph is empty”,是什么问题呀?大神们帮忙解决一下!

原始代码是

import tensorflow as tf
a = tf.constant("Hello,world!")
sess = tf.Session()
print(sess.run(a))
sess.close()

这个显示错误:**module 'tensorflow' has no attribute 'Session'**

后按照网上提示,只有tensorflow 1 有,于是改成了下面的:

import tensorflow as tf
a = tf.constant("Hello,world!")
sess = tf.compat.v1.Session()
print(sess.run(a))
sess.close()

这个还是有错误,显示“The session graph is empty”
Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Traceback (most recent call last):
File "C:/Users/Dell/PycharmProjects/Helloworld/helloWorldTen.py", line 5, in
print(sess.run(a))
File "E:\Anaconda3\lib\site-packages\tensorflow_core\python\client\session.py", line 956, in run
run_metadata_ptr)
File "E:\Anaconda3\lib\site-packages\tensorflow_core\python\client\session.py", line 1105, in _run
raise RuntimeError('The Session graph is empty. Add operations to the '
RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

import tensorflow as tf
tf.compat.v1.disable_eager_execution() #保证sess.run()能够正常运行
hello = tf.constant('hello,tensorflow')
sess= tf.compat.v1.Session()#版本2.0的函数
print(sess.run(hello))
-------这样就解决了

下面有两个解决方法:

import tensorflow as tf

s = tf.compat.v1.Session()
with tf.compat.v1.get_default_graph().as_default():
    h = tf.constant('Hello, this is TensorFlow')
    print(s.run(h))
import tensorflow as tf

tf.compat.v1.disable_eager_execution()
a = tf.constant('Hello, TensorFlow!')
sess = tf.compat.v1.Session()
print(sess.run(a))
sess.close()

https://blog.csdn.net/mangobar/article/details/99312004