How to run a python script from IDLE interactive shell?
Asked Answered
F

15

132

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

The following throws an error:

>>> python helloworld.py
SyntaxError: invalid syntax
Frohman answered 22/6, 2013 at 5:3 Comment(6)
What does helloworld.py look like?Analog
yeah it means something is wrong with youre code post youre code!Beagle
No, not necessarily. Chances are the OP is typing python helloworld.py in an IDLE shell window and that doesn't work.Scherer
Nor would it work in the standard interpreter. This issue has come up before where people mistakenly think that the interpreter prompt is a command-line prompt.Suicide
You should accept the answer from Ned Deily if that answer your question correctly. This will also help fellow developers to quickly spot the correct answer.Ternan
EASIEST WAY: python -i helloworld.py also works for python3Ca
H
191

Python3:

exec(open('helloworld.py').read())

If your file not in the same dir:

exec(open('./app/filename.py').read())

See https://mcmap.net/q/13906/-what-is-an-alternative-to-execfile-in-python-3 for passing global/local variables.

Note: If you are running in windows you should use double slash "//" otherwise it gives error


In deprecated Python versions

Python2 Built-in function: execfile

execfile('helloworld.py')

It normally cannot be called with arguments. But here's a workaround:

import sys
sys.argv = ['helloworld.py', 'arg']  # argv[0] should still be the script name
execfile('helloworld.py')

Deprecated since 2.6: popen

import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout

With arguments:

os.popen('python helloworld.py arg').read()

Advance usage: subprocess

import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout

With arguments:

subprocess.call(['python', 'helloworld.py', 'arg'])

Read the docs for details :-)


Tested with this basic helloworld.py:

import sys
if len(sys.argv) > 1:
    print(sys.argv[1])
Handshaker answered 8/2, 2014 at 19:21 Comment(3)
Can you please add an example with command line arguments as well.Fossil
Doesn't work with Python3 and asker didn't specify Python version explicitlyStormy
Added exec for Python3Handshaker
A
42

You can use this in python3:

exec(open(filename).read())
Agnail answered 1/12, 2016 at 9:30 Comment(0)
S
27

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).

Scherer answered 22/6, 2013 at 5:18 Comment(4)
But you can't pass in arguments. :(Rhizobium
Unfortunately, no, it's not easy to run a Python file in IDLE while passing in command line arguments. There is a long-standing open issue for IDLE to do so (bugs.python.org/issue5680). One workaround for testing is to manually initialize sys.argv at the very beginning of the program, for example, under the usual if __name__ == "__main__" boilerplate.Scherer
This answer clarifies why we can not run python script using IDLE shell. Thanks @NedDeilyWithin
As of IDLE 3.7.4, you can now run a module with arguments. Use the new Run -> Run with Customized... command (shortcut Shift+F5) and a popup will open where you can supply your arguments. Unfortunately it doesn't remember them currently so you'll be pasting them with every run.Marivelmariya
C
10

EASIEST WAY

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3
Ca answered 2/8, 2018 at 5:8 Comment(0)
J
5

Try this

import os
import subprocess

DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')

subprocess.call(['python', DIR])
Jonquil answered 14/3, 2015 at 8:8 Comment(0)
P
4

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')

Passible answered 10/10, 2014 at 21:56 Comment(0)
F
4

In a python console, one can try the following 2 ways.

under the same work directory,

1. >> import helloworld

# if you have a variable x, you can print it in the IDLE.

>> helloworld.x

# if you have a function func, you can also call it like this.

>> helloworld.func()

2. >> runfile("./helloworld.py")

Frankpledge answered 3/7, 2020 at 15:50 Comment(0)
J
2

For example:

import subprocess

subprocess.call("C:\helloworld.py")

subprocess.call(["python", "-h"])
Jonquil answered 13/3, 2015 at 20:24 Comment(2)
subprocess.call(r'c:\path\to\something.py') does not work for me. OSError: [WinError 193] %1 is not a valid Win32 applicationSuicide
Try this import os import subprocess DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'a.py') subprocess.call(['python', DIR])Jonquil
W
1

In Python 3, there is no execFile. One can use exec built-in function, for instance:

import helloworld
exec('helloworld')
Wonderful answered 8/3, 2016 at 12:25 Comment(0)
G
1

In IDLE, the following works :-

import helloworld

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

Glarus answered 8/7, 2016 at 15:12 Comment(2)
what you are doing is loading a module not running from shell. one difference between two is: 1) Loading module your module name name__= name of file 2) run from shell module name _name__="_main"Odeen
It is not a good way to run programs because you are actually importing and not running it. Its contents will be imported and it will be meaningless if you don't want to utilise them.Synaeresis
G
1

To run a python script in a python shell such as Idle or in a Django shell you can do the following using the exec() function. Exec() executes a code object argument. A code object in Python is simply compiled Python code. So you must first compile your script file and then execute it using exec(). From your shell:

>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)

I'm using Python 3.4. See the compile and exec docs for detailed info.

Glandular answered 12/9, 2016 at 19:27 Comment(0)
S
1

I tested this and it kinda works out :

exec(open('filename').read())  # Don't forget to put the filename between ' '
Saddleback answered 13/8, 2017 at 13:39 Comment(1)
thanks for the quotation tip, this worked for me. Upvoted.Malapropism
C
1

you can do it by two ways

  • import file_name

  • exec(open('file_name').read())

but make sure that file should be stored where your program is running

Cloverleaf answered 8/12, 2018 at 14:34 Comment(0)
P
1

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
Plummer answered 3/1, 2019 at 23:23 Comment(1)
importing a program to run it is not a good option. Even I used it in beginning but now I know about potential problems like it takes away the effeciency of your program because you are importing it (though negligible).Synaeresis
S
0

There is one more alternative (for windows) -

    import os
    os.system('py "<path of program with extension>"')
Synaeresis answered 16/5, 2020 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.