Skip to content Skip to sidebar Skip to footer

How To Run A.py File In Python Cmd?

I'm a newbie to python, so I just installed python27 on my win8 machine and set the path for C:\Python27 and C:\Python27\Scripts. Now I want to execute a small .py file, so at the

Solution 1:

  1. Treat it like a module:

    import file 
    

    This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that your import should not include the .py extension at the end.

  2. Use the exec command:

    execfile('file.py')
    

    But this is likely to go wrong very often and is kind of hacky.

  3. Spawn a shell process:

    import subprocess
    import sys
    
    subprocess.check_call([sys.executable, 'file.py'])
    

    Use when desperate.


Post a Comment for "How To Run A.py File In Python Cmd?"