Is there a possibility to execute a Python script

2019-01-30 23:14发布

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.

6条回答
▲ chillily
2楼-- · 2019-01-30 23:25

You can run any system command using python:

>>>from subprocess import Popen
>>>Popen("python myscript.py", shell=True)
查看更多
放荡不羁爱自由
3楼-- · 2019-01-30 23:26

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

查看更多
别忘想泡老子
4楼-- · 2019-01-30 23:35

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.

查看更多
Juvenile、少年°
5楼-- · 2019-01-30 23:37

You can also use the subprocess module. Something like:

>>> import subprocess
>>> proc = subprocess.Popen(['./script.py'])
>>> proc.communicate()
查看更多
Animai°情兽
6楼-- · 2019-01-30 23:44

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

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-30 23:45

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)

查看更多
登录 后发表回答