Is there a possibility to execute a Python script while being in interactive mode

PythonInteractiveMode

Python Problem Overview


Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?

>>> exec(File) ???

It should be possible to execute the script more than one time.

Python Solutions


Solution 1 - Python

Use execfile('script.py') but it only work on python 2.x, if you are using 3.0 try this

Solution 2 - Python

import file without the .py extension will do it, however __name__ will not be "__main__" so if the script does any checks to see if it's being run interactively you'll need to bypass them.

Alternately, if you're wanting to have a look at the environment after the script runs try python -i script.py

EDIT: To load it again

file = reload(file)

Solution 3 - Python

You might want to look into IPython, a more powerful interactive shell. It has various "magic" commands including %run script.py (which, of course, runs the script and leaves any variables it defined for you to examine).

Solution 4 - Python

You can also use the subprocess module. Something like:

>>> import subprocess
>>> proc = subprocess.Popen(['./script.py'])
>>> proc.communicate()

Solution 5 - Python

You can run any system command using python:

>>>from subprocess import Popen
>>>Popen("python myscript.py", shell=True)

Solution 6 - Python

The easiest way to do it is to use the os module:

import os

os.system('python script.py')

In fact os.system('cmd') to run shell commands. Hope it will be enough.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlennykeyView Question on Stackoverflow
Solution 1 - Pythonfn.View Answer on Stackoverflow
Solution 2 - PythonrichoView Answer on Stackoverflow
Solution 3 - PythonThomas KView Answer on Stackoverflow
Solution 4 - PythonSylvain DefresneView Answer on Stackoverflow
Solution 5 - PythonSilver LightView Answer on Stackoverflow
Solution 6 - PythonCipherView Answer on Stackoverflow