[英]run program in Python shell
我有一個演示文件: test.py
。 在 Windows 控制台中,我可以使用以下命令運行該文件: C:\\>test.py
如何在 Python Shell 中執行文件?
如果您想運行腳本並在提示處結束(以便您可以檢查變量等),請使用:
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 文件。
對於較新版本的python:
exec(open(filename).read())
如果你想避免每次都寫這些,你可以定義一個函數:
def run(filename):
exec(open(filename).read())
然后調用它
run('filename.py')
在同一個文件夾中,您可以執行以下操作:
import test
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.