5

In a bash shell, I can use 'bash ' or 'source ' to invoke a script by hand. Can I do the similar thing in the Python IDLE's interactive shell? I know I can go to File >> Open Module, then run it in a separate window, but that's troublesome.

3 Answers 3

4

One method I have found is execfile. It has the signature execfile(<filename>,<globals>,<locals>) and runs the file in the same thread as the current IDLE Session. This method is Python 2 specific

The method the OP is asking for (in a different thread/window) would be to use subprocess to run in a different thread/window.

import subprocess

#any of these will run the file.  Pick the one that best suits you.

subprocess.call(['python','filename.py'])
subprocess.check_call(['python','filename.py'])
subprocess.Popen(['python','filename.py'])

These essentially do what nneonneo's answer does, but using subprocess to execute it in a different thread.

Sign up to request clarification or add additional context in comments.

2 Comments

execfile() only works in Python 2.x. It's been removed in Python 3: python3porting.com/differences.html, where 'exec(open(thefile).read())' can be used, which returns the output back to the IDLE interactive shell, but I haven't figured out a way to pass the command line arguments. subprocess would work but it doesn't return the outputs, and requires more trouble to get it (though probably do-able). This is nothing compared to the "." operator in bash to execute a script. Too bad.
@HaiXinTie Thanks for noting that. I've updated the answer to reflect that fact.
1

If what you meant is executing in the Python IDLE's interactive shell instead of command prompt or command line, then I usually use this approach:

python -m idlelib.idle -r "C:/dir1/dir2/Your script.py"

It works well with me. Tested on my Windows 10, python 3.7.3.

Please ensure that you have added your desired python version on your environment variables.

Comments

0

You can just run a Python script from the commandline:

python <script.py>

1 Comment

I think the asker is looking for a way to do it inside the interactive shell, not just command line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.