Run Python Script File

来源:互联网 发布:网络维护员工作内容 编辑:程序博客网 时间:2024/05/22 14:20

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 syssys.argv = ['ex1.py', 'arg']  # argv[0] should still be the script nameexecfile('ex1.py')

Trick 2: Use popen

import osos.popen('python ex1.py') # Just run the programos.popen('python ex1.py').read() # Also gets you the stdout

Tick 3: Use subprocess

import subprocesssubprocess.call(['python', 'ex1.py']) # Just run the programsubprocess.check_output(['python', 'ex1.py']) # Also gets you the stdoutsubprocess.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.