简体   繁体   中英

How to execute Python scripts with python command

I want to run the Python Script by using python command from IDLE Python GUI.
The location of the file is C:\\Users\\DELL\\Desktop\\Hello.py
When I run python C:\\Users\\DELL\\Desktop\\Hello.py with Windows command promt, it works. However, when I try with IDLE Python GUI and Python (command line), it does not work and gives me a message SyntaxError: invalid syntax
Capture

inside python shell, you can import the module. This way, you can see "Hello" printed on shell once u import it.

>>> import sys
>>> sys.path.append('C:\Users\DELL\Desktop')
>>> import Hello
"Hello"

When using IDLE, you are already "inside" python (in its REPL)..
You should "load" (import) the file instead..
See here https://stackoverflow.com/a/21650698/5121955 (exact same situation), where you can find many solutions with their advantages..

You cannot do this from the Python interpreter, since this is not Python syntax, if you want to do this it has to be from command prompt or execute it as a system command:

import os
os.system('python  C:\\Users\\DELL\Desktop\\Hello.py')

Or use subprocess.call

If you want to run your python file from another Python file see How can I make one python file run another?

If you want to run it from the IDLE simply select open and navigate to the desired location and select run.

If it is executable script (as you stated, it works from command line with the python command), you should be able to execute it directly from python with the following statements

import os
os.system("C:\\Users\\DELL\\Desktop\\Hello.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