0

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

user2957951
  • 303
  • 2
  • 4
  • 11

1 Answers1

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.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • Thanks Alex: But I'm not sure, I understand :( you'll have to dumb it down for me. I tried typing import gtos.py and I get the same syntax error. Maybe I'm missing an interpreter or something!!! what I type I get syntax error!!! – user2957951 Feb 22 '14 at 22:02
  • Some advice for SO: when you read an answer, read the whole answer- you learn alot more looking at explanations and other solutions. I said when importing a file, do not use the file extension. :) – anon582847382 Feb 22 '14 at 22:07
  • THAT DID IT (no extension). THANKS ALEX! – user2957951 Feb 22 '14 at 22:11
  • 1
    the 2nd and 3rd options are much more rare than the 1st (`import module`). There is even no `execfile()` in Python 3 any more. And `subprocess.check_call([sys.executable, 'module.py'])` could be used instead of `os.system()`. – jfs Feb 22 '14 at 22:24
  • Don't use `shell=True` unless it is necessary (and it is not here). – jfs Feb 22 '14 at 22:38