user2957951
user2957951

Reputation: 313

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 shell (python cmd) I type:

python "c:\python27\gtos.py"

  File "<stdin>", line 1

  python "c:\python27\gtos.py"
                               ^

SyntaxError: invalid syntax

Any help is appreciated...

Thanks

Upvotes: 0

Views: 5317

Answers (1)

anon582847382
anon582847382

Reputation: 20391

  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.

Upvotes: 1

Related Questions