如何在python cmd中运行.py文件? [英] How to run a.py file in python cmd?

查看:73
本文介绍了如何在python cmd中运行.py文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,所以我刚刚在我的win8机器上安装了python27并设置了C:\Python27和C:\Python27\Scripts的路径.

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.

现在我想执行一个小的 .py 文件,所以在 shell (python cmd) 中我输入:

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

感谢任何帮助...

谢谢

推荐答案

  1. 把它当作一个模块来对待:

  1. Treat it like a module:

import file 

这很好,因为它安全、快速且可维护.代码被重用,因为它应该完成.大多数 Python 库使用跨越大量文件的多种方法运行.强烈推荐.请注意,您的导入不应在末尾包含 .py 扩展名.

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.

使用 exec 命令:

Use the exec command:

execfile('file.py')

但这很可能经常出错,而且有点老套.

But this is likely to go wrong very often and is kind of hacky.

产生一个shell进程:

Spawn a shell process:

import subprocess
import sys

subprocess.check_call([sys.executable, 'file.py'])

绝望时使用.

这篇关于如何在python cmd中运行.py文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆