python - 从 Python Shell 运行 Python 脚本

标签 python

我编写了一个脚本并将其保存为 test.py(代码如下所示)。当我从脚本(运行模块 5)运行它时,我在 Python Shell 中得到了结果。

但我已经尝试了多种在线建议,让它从 Python Shell 运行,但我失败了(下面粘贴了一个错误)。

如何从 python shell 运行 python 脚本? 我运行的 Python 版本是 3.7.3,在 Windows 中。

#!/usr/bin/python3

print(" Hello, world!")

exec(open(test.py).read())

输出:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    exec(open(test.py).read())
NameError: name 'test' is not defined

最佳答案

你不需要最后一行来运行它。您只需要:

!/usr/bin/python3

print(" Hello, world!")

如果你想从另一个文件运行它,不要使用 exec。相反,导入它。

import test

关于python - 从 Python Shell 运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498247/

相关文章:

python - 根据带有 basemap 的字典值对一个国家/地区的状态进行着色

python - 当我从批处理文件和任务计划程序运行脚本时,子进程运行、check_output、Popen 返回空字符串

python - 具有长度的对象的类型

python - 在 python 中将 dbf 转换为 csv 的方法?

python - 在 Tornado/Python 中以非阻塞方式写入日志文件

python - 在 GPU 上训练 RNN - 我应该使用哪个 tf.keras 层?

Python postgreSQL 非常慢

python - 如何使用 Python 设置网络摄像头服务器?

python - 根据一个字典删除另一个字典中的某些元素

python - 在 nginx 后面使用带有cherrypy 的 session RamSession 时出错