简体   繁体   中英

Executing python code

I am starting fresh with python and trying to execute a code from the python command window. I wrote a file on Desktop\\practice\\new.py and lunched the python command window.

when I type

C:\users\user\Desktop\practice\new.py

it gives me

SyntaxError: invalid syntax 

Executing from CMD worked, but from python window didnt!

Any help?

EDIT2: when i put the compiled code in the directory and use the 'import' it runs, but when the compiled is not in the same directory it won't execute

EDIT: the file contains a simple print statement nd is sytax error free

Everything is explained in here: http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows

The main point that when you launch python shell. Its like a live programming. Try to type in it:

>>> print 'hello world'

If you want to launch your file - run in cmd: python C:/users/user/Desktop/practice/new.py

UPDATE: If you do want to run file from within python shell - it was answered here: How to execute a file within the python interpreter?

When you say you're using the "python command window" I'm guessing you mean IDLE...? If so, rather than try to type a command to run a script you've already created as a file, just use File > Open to open that file and then press F5 to run it. Good luck!

The python command window is expecting python commands. Try typing 'import system' or 'print 1+2'.

If you want to run the code in another file you need to use 'import'. Its easier if you start in the same directory, in which case just doing 'import new' will work.

However, there's already a 'new' module in the python library, so the easiest thing to do is to rename your file something else...

It is not working because you are entering the path like c:\\users\\user\\desktop\\practice\\new.py.....

now try this way: c:/users/user/desktop/practice/new.py
I hope this will work for you ie just change '\\' to '/' have a try...

您可以这样运行文件:

execfile(r'C:\users\user\Desktop\practice\new.py')

Edit: read the comments below this answer before trying it!

Try this:

import sys
sys.path.append("C:\users\user\Desktop\practice\")
import new #won't work - call it something other than new.py...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM