简体   繁体   English

从Python Shell运行Python脚本

[英]Running a Python script from the Python Shell

I wrote a script and saved it as test.py (code shown below). 我写了一个脚本并将其保存为test.py(代码如下所示)。 And when I run it from the script (Run Module 5), I get the result in the Python Shell. 当我从脚本(运行模块5)运行它时,我在Python Shell中获得结果。

But I have tried multiple suggestions available online to have it run from the Python Shell instead to which I fail (one error pasted below). 但我已经尝试了多种在线提供的建议,让它从Python Shell运行而不是我失败了(下面粘贴了一个错误)。

How can I run a python script from the python shell? 如何从python shell运行python脚本? The version of Python I am running is 3.7.3 and in Windows. 我运行的Python版本是3.7.3,在Windows中。

#!/usr/bin/python3

print(" Hello, world!")

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

Output: 输出:

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

You don't need the last line for it to run. 您不需要最后一行来运行它。 All you need is: 所有你需要的是:

!/usr/bin/python3

print(" Hello, world!")

If you want to run it from another file, don't use exec. 如果要从其他文件运行它,请不要使用exec。 Instead, import it. 而是导入它。

import test

You need to pass the "test.py" as a string (use quotes). 您需要将“test.py”作为字符串传递(使用引号)。 test is not a known object. 测试不是一个已知的对象。

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

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