Run Python Script File

Make Installed Python Recognized by System

After we installed Python 2.7, Python by default is not recognized by Windows system so that you can directly type pythoncommand in terminal console to initiate the program.
To make it available we need to add Python executive path as a system Environment Variable. Generally there are two ways to make it happen:

Method 1: Through Windows Built-in Program PowerShell

Type the following command in PowerShell command line and enter:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

Then close PowerShell and then start it again.

Method 2: Manually Add the Path through Windows GUI

Please refer to Add Python to the PATH Environmental Variable (‘python’ is not recognized as an internal or external command) and follow detailed steps in PythonCentral website to finish.

Run Python Script from IDLE Interactive Shell

Normally after you make python program being aware of by the system, the next thing most would try is to run a python file directly in IDLE Shell by typing the following command:

python helloworld.py

Most of the time you should receive the output:

Syntax Error:invalid syntax

To run a Python file in IDLE shell, it is mostly suggested to directly open the file through GUI menu and run it use F5.

If you insist on running some command lines to initiate, you can try the following workaround as posted in stack overflow website. Here I will just quote several wa# Run Python File from Shell

Trick 1: Use execfile
import sys
sys.argv = ['ex1.py', 'arg']  # argv[0] should still be the script name
execfile('ex1.py')
Trick 2: Use popen
import os
os.popen('python ex1.py') # Just run the program
os.popen('python ex1.py').read() # Also gets you the stdout
Tick 3: Use subprocess
import subprocess
subprocess.call(['python', 'ex1.py']) # Just run the program
subprocess.check_output(['python', 'ex1.py']) # Also gets you the stdout
subprocess.call(['python', 'ex1.py', 'arg'])

Run Python File from Shell

Run Python Script File from Notepad++

Run Python Script File from PowerShell

If you directly run command below once you launched PowerShell:

python ex1.py

You can see the following error message:

*C:\Python27\python.exe: can't open file 'ex1.py': [Errno 2] No such file or directory*

It means you change your current working folder using

cd

Find the path of the folder you place your python files in, copy and right click to paste it right after command cd.

 1. cd C:\Python27 
 2. python ex1.py

Then you file is executed and results are outputted to PowerShell console.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值