How to run a python script from IDLE interactive shell?

前端 未结 15 1857
無奈伤痛
無奈伤痛 2020-11-30 17:25

How do I run a python script from within the IDLE interactive shell?

The following throws an error:

>>> python helloworld.py
SyntaxError: i         


        
15条回答
  •  自闭症患者
    2020-11-30 18:25

    On Windows environment, you can execute py file on Python3 shell command line with the following syntax:

    exec(open('absolute path to file_name').read())

    Below explains how to execute a simple helloworld.py file from python shell command line

    File Location: C:/Users/testuser/testfolder/helloworld.py

    File Content: print("hello world")

    We can execute this file on Python3.7 Shell as below:

    >>> import os
    >>> abs_path = 'C://Users/testuser/testfolder'
    >>> os.chdir(abs_path)
    >>> os.getcwd()
    'C:\\Users\\testuser\\testfolder'
    
    >>> exec(open("helloworld.py").read())
    hello world
    
    >>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
    hello world
    
    >>> os.path.abspath("helloworld.py")
    'C:\\Users\\testuser\\testfolder\\helloworld.py'
    >>> import helloworld
    hello world
    

提交回复
热议问题