How to run a python script from IDLE interactive shell?

前端 未结 15 1811
無奈伤痛
無奈伤痛 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:14

    execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)

    For example, execFile('C:/helloworld.py')

    0 讨论(0)
  • 2020-11-30 18:16

    EASIEST WAY

    python -i helloworld.py  #Python 2
    
    python3 -i helloworld.py #Python 3
    
    0 讨论(0)
  • 2020-11-30 18:16

    In IDLE, the following works :-

    import helloworld

    I don't know much about why it works, but it does..

    0 讨论(0)
  • 2020-11-30 18:22

    I tested this and it kinda works out :

    exec(open('filename').read())  # Don't forget to put the filename between ' '
    
    0 讨论(0)
  • 2020-11-30 18:24

    The IDLE shell window is not the same as a terminal shell (e.g. running sh or bash). Rather, it is just like being in the Python interactive interpreter (python -i). The easiest way to run a script in IDLE is to use the Open command from the File menu (this may vary a bit depending on which platform you are running) to load your script file into an IDLE editor window and then use the Run -> Run Module command (shortcut F5).

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题