How do I run a python script from within the IDLE interactive shell?
The following throws an error:
>>> python helloworld.py
SyntaxError: i
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')
EASIEST WAY
python -i helloworld.py #Python 2
python3 -i helloworld.py #Python 3
In IDLE, the following works :-
import helloworld
I don't know much about why it works, but it does..
I tested this and it kinda works out :
exec(open('filename').read()) # Don't forget to put the filename between ' '
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).
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