How do I run a python script from within the IDLE interactive shell?
The following throws an error:
>>> python helloworld.py
SyntaxError: invalid syntax
Python3:
exec(open('helloworld.py').read())
If your file not in the same dir:
exec(open('./app/filename.py').read())
See https://stackoverflow.com/a/437857/739577 for passing global/local variables.
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])
You can use this in python3:
exec(open(filename).read())
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).
EASIEST WAY
python -i helloworld.py #Python 2
python3 -i helloworld.py #Python 3
Try this
import os
import subprocess
DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')
subprocess.call(['python', DIR])
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')
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")
For example:
import subprocess
subprocess.call("C:\helloworld.py")
subprocess.call(["python", "-h"])
In Python 3, there is no execFile. One can use exec built-in function, for instance:
import helloworld
exec('helloworld')
In IDLE, the following works :-
import helloworld
I don't know much about why it works, but it does..
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.
I tested this and it kinda works out :
exec(open('filename').read()) # Don't forget to put the filename between ' '
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
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
There is one more alternative (for windows) -
import os
os.system('py "<path of program with extension>"')
Related
I executed this code in python: (test.py)
from subprocess import Popen
p = Popen("file.bat").wait()
Here is file.bat:
#echo off
start c:\python27\python.exe C:\Test\p1.py %*
start c:\python27\python.exe C:\Test\p2.py %*
pause
Here is p1.py:
This line is error
print "Hello word"
p2.py is not interesting
I want to know the exception(not only compiling error) in p1.py by running test.py?
How can I do this?
Thanks!
Here's how I got it working:
test.py
from subprocess import Popen
p = Popen(["./file.sh"]).wait()
Make sure to add the [] around file, as well as the ./. You can also add arguments, like so:
["./file.sh", "someArg"]
Note that I am not on Windows, but this fixed it on Ubuntu. Please comment if you are still having issues
EDIT:
I think the real solution is: Using subprocess to run Python script on Windows
This way you can run a python script from python, while still using Popen
The python script I would use (source code here) would parse some arguments when called from the command line. However, I have no access to the Windows command prompt (cmd.exe) in my environment. Can I call the same script from within a Python console? I would rather not rewrite the script itself.
%run is a magic in IPython that runs a named file inside IPython as a program almost exactly like running that file from the shell. Quoting from %run? referring to %run file args:
This is similar to running at a system prompt python file args,
but with the advantage of giving you IPython's tracebacks, and of
loading all variables into your interactive namespace for further use
(unless -p is used, see below). (end quote)
The only downside is that the file to be run must be in the current working directory or somewhere along the PYTHONPATH. %run won't search $PATH.
%run takes several options which you can learn about from %run?. For instance: -p to run under the profiler.
If you can make system calls, you can use:
import os
os.system("importer.py arguments_go_here")
You want to spawn a new subprocess.
There's a module for that: subprocess
Examples:
Basic:
import sys
from subprocess import Popen
p = Popen(sys.executable, "C:\test.py")
Getting the subprocess's output:
import sys
from subprocess import Popen, PIPE
p = Popen(sys.executable, "C:\test.py", stdout=PIPE)
stdout = p.stdout
print stdout.read()
See the subprocess API Documentation for more details.
I am trying out the sys library in python. In command prompt I am using this.
>>>import sys
>>>sys.ps1 ='$'
#my own input 'print 'test print''
$print 'test print'
test print
That worked in CLI, however, when I tried to do it in a python file and run it in CLI ( python file.py did not return anything.
#!/usr/bin/python
import sys
sys.ps1= '$'
Am I missing anything in the file?
What are you trying to do? sys.ps1 will just set the prompt for the python interpreter, so as soon as it exits it's effect is gone again. When running a file, there is no command-line.
If you want to see this have an effect, try running this with python -i file.py - this will run the command, and then drop you into the interactive shell, which should have PS1 set to $ now
I have a demo file: test.py.
In the Windows Console I can run the file with: C:\>test.py
How can I execute the file in the Python Shell instead?
Use execfile for Python 2:
>>> execfile('C:\\test.py')
Use exec for Python 3
>>> exec(open("C:\\test.py").read())
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
python -i test.py
That will run the script and then drop you into a Python interpreter.
It depends on what is in test.py. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
For newer version of python:
exec(open(filename).read())
If you want to avoid writing all of this everytime, you can define a function :
def run(filename):
exec(open(filename).read())
and then call it
run('filename.py')
From the same folder, you can do:
import test
So, I created a simple python module, test.py
import commands
def main():
cmd = 'ls -l'
(status, output) = commands.getstatusoutput(cmd)
print status, output
if __name__ == '__main__':
main()
When I ran it using "Python test.py", I got the result that I expected. But when I ran it as an executable (yes, it has the 'x' permission), the program didn't respond at all and I had to Ctrl+C to quit it. Why is that? Shouldn't both ways give the same result?
Add a hash-bang line to the top:
#!/usr/bin/env python
import commands
...
This tells your system what interpreter to use to execute the script. Without it it doesn't know if it's a shell script, Perl script, Python script, what.
You need the hashbang to be the first line of your script, referencing the path of the Python interpreter. Otherwise, all the OS knows is that you're trying to execute a script, and it has no idea how to go about doing that.