我有一个演示文件:test.py
。
在Windows控制台中,我可以使用以下方式运行该文件:C:\>test.py
那如何在Python Shell中执行该文件呢?
我有一个演示文件:test.py
。
在Windows控制台中,我可以使用以下方式运行该文件:C:\>test.py
那如何在Python Shell中执行该文件呢?
SyntaxError: (Unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX excape
。这是什么意思?我尝试将我的.py文件的编码更改为Unicode,但没有任何效果。 - Musixauce3000\U
Unicode转义。显然,通过复制所有后面跟着U的反斜杠来避免这种误传。但是这会产生一个OSError 22无效参数'c:\\ users \ username \\ desktop \\ test.py'
,这很奇怪,因为我只复制了\Users
中的反斜杠。为什么错误显示我复制了除用户名后面的所有反斜杠? - Musixauce3000如果您想要运行脚本并以提示符结束(以便您可以检查变量等),那么请使用:
python -i test.py
这将运行脚本并将您带入Python解释器。
这要看test.py
中有什么内容。以下是一个合适的结构:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
如果您保持这种结构,则可以在命令行中像这样运行它(假设$
是您的命令行提示符):
$ python test.py
$ # it will print "running main"
如果您想从Python shell中运行它,那么您只需要执行以下操作:>>> import test
>>> test.main() # this calls the main part of your program
如果你已经在使用 Python,那就没有必要再使用 subprocess
模块了。相反,尝试将你的 Python 文件结构化,使它们可以在命令行和 Python 解释器中都能运行。
如果你想避免每次都写这些内容,你可以定义一个函数:
def run(filename):
exec(open(filename).read())
接着调用它
run('filename.py')
针对较新版本的Python:
exec(open(filename).read())
从同一个文件夹中,您可以执行以下操作:
import test
python
吗?还是使用IDLE或其他可以提供Python>>>
提示的程序? - S.Lott