How to run a python script from IDLE interactive shell?

前端 未结 15 1917
無奈伤痛
無奈伤痛 2020-11-30 17:25

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

The following throws an error:

>>> python helloworld.py
SyntaxError: i         


        
15条回答
  •  余生分开走
    2020-11-30 18:08

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

提交回复
热议问题