繁体   English   中英

从Python Shell运行Python脚本

[英]Running a Python script from the Python Shell

我写了一个脚本并将其保存为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

您需要将“test.py”作为字符串传递(使用引号)。 测试不是一个已知的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM