Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a Python script from IDLE command line?

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.

like image 224
HaiXin Tie Avatar asked Mar 14 '13 01:03

HaiXin Tie


People also ask

How do I run a Python script from command line?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do I run a Python script from line by line?

Interactive Mode: In Interactive Mode, you can run your script line by line in a sequence. To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ' python ' and press Enter .


1 Answers

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.

like image 78
Snakes and Coffee Avatar answered Sep 18 '22 23:09

Snakes and Coffee