How to run a python script from IDLE interactive s

2020-01-27 09:32发布

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

The following throws an error:

>>> python helloworld.py
SyntaxError: invalid syntax

13条回答
The star\"
2楼-- · 2020-01-27 10:16

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

import helloworld
exec('helloworld')
查看更多
戒情不戒烟
3楼-- · 2020-01-27 10:19

You can use this in python3:

exec(open(filename).read())
查看更多
一纸荒年 Trace。
4楼-- · 2020-01-27 10:19

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

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-01-27 10:20

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
查看更多
Luminary・发光体
6楼-- · 2020-01-27 10:25

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

查看更多
啃猪蹄的小仙女
7楼-- · 2020-01-27 10:27

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

查看更多
登录 后发表回答