系统命令行和文件——命令行用法变化

未匹配的标注

因为这个方法使用了shell命令行来启动Python程序,所有常用的shell语法都适用。比如,你可以通过使用特殊的shell语法将Python脚本的打印结果转到一个文件中保存以备随后使用或检查:

% python script1.py > saveit.txt

在本例中,在先前例子中出现的三个输出行被保存到文件 saveit.txt 而不是被打印出来。这通常被称为流重定向;它适用于输入和输出文本且在Windows和类Unix系统上可用。这很适合测试,因为你可以编写程序来监控其他程序输出中的变化。它还和Python关系不大,虽然(Python简单地支持它),所以我们在这里将忽略掉关于shell重定向语法的进一步细节。

注:下面的都是windows平台上的细节,不再翻译

If you are working on a Windows platform, this example works the same, but the system prompt is normally different as described earlier:

C:\code> python script1.py
win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

As usual, if you haven’t set your PATH environment variable to include the full directory path to python, be sure to include this in your command, or run a change-directory command to go to the path first:

C:\code> C:\python33\python script1.py
win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

Alternatively, if you’re using the Windows launcher new in Python 3.3 (described earlier), a py command will have the same effect, but does not require a directory path or PATH settings, and allows you to specify Python version numbers on the command line too:

c:\code> py −3 script1.py
win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

On all recent versions of Windows, you can also type just the name of your script, and omit the name of Python itself. Because newer Windows systems use the Windows Registry (a.k.a. filename associations) to find a program with which to run a file, you don’t need to name “python” or “py” on the command line explicitly to run a .py file. The prior command, for example, could be simplified to the following on most Windows machines, and will automatically be run by python prior to 3.3, and by py in 3.3 and later—just as though you had clicked on the file’s icon in Explorer (more on this option ahead):

C:\code> script1.py

Finally, remember to give the full path to your script file if it lives in a different directory from the one in which you are working. For example, the following system command line, run from D:\other, assumes Python is in your system path but runs a file located elsewhere:

C:\code> cd D:\other
D:\other> python c:\code\script1.py

If your PATH doesn’t include Python’s directory, you’re not using the Windows launcher’s py program, and neither Python nor your script file is in the directory you’re working in, use full paths for both:

D:\other> C:\Python33\python c:\code\script1.py

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~