简体   繁体   English

如何使用python命令执行Python脚本

[英]How to execute Python scripts with python command

I want to run the Python Script by using python command from IDLE Python GUI. 我想通过使用IDLE Python GUI中的python命令来运行Python脚本。
The location of the file is C:\\Users\\DELL\\Desktop\\Hello.py 该文件的位置是C:\\ Users \\ DELL \\ Desktop \\ Hello.py
When I run python C:\\Users\\DELL\\Desktop\\Hello.py with Windows command promt, it works. 当我使用Windows命令promt运行python C:\\Users\\DELL\\Desktop\\Hello.py时,它可以工作。 However, when I try with IDLE Python GUI and Python (command line), it does not work and gives me a message SyntaxError: invalid syntax 但是,当我尝试使用IDLE Python GUI和Python(命令行)时,它不起作用,并显示一条消息SyntaxError: invalid syntax
Capture 捕获

inside python shell, you can import the module. 在python shell中,您可以import模块。 This way, you can see "Hello" printed on shell once u import it. 这样,导入后即可在外壳上看到“ Hello”字样。

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

When using IDLE, you are already "inside" python (in its REPL).. 使用IDLE时,您已经在python内部(在其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.. 请参阅https://stackoverflow.com/a/21650698/5121955 (完全相同的情况),在这里您可以找到许多具有其优势的解决方案。

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: 您不能通过Python解释器执行此操作,因为这不是Python语法,如果要执行此操作,则必须从命令提示符处执行或将其作为系统命令执行:

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

Or use subprocess.call 或使用subprocess.call

If you want to run your python file from another Python file see How can I make one python file run another? 如果要从另一个Python文件运行python文件,请参见如何使一个python文件运行另一个?

If you want to run it from the IDLE simply select open and navigate to the desired location and select run. 如果要从IDLE运行它,只需选择open并导航到所需位置,然后选择运行。

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 如果它是可执行脚本(如您所述,它可以通过python命令从命令行运行),则应该能够使用以下语句直接从python执行它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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