如何将命令提示符中的 Python 编码保存为文件? [英] How to save Python coding in Command Prompt as a file?

查看:51
本文介绍了如何将命令提示符中的 Python 编码保存为文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 Python34 的书中键入了一个正在运行的命令提示符的示例.

I just typed an example from a book in Python34 of a running Command Prompt.

但现在我想将这个 python 程序保存为文件以备将来使用.由于我之前从未使用过命令提示符,我也在网上搜索过,但大多数都无法回答.

but now I want to save this python program as file for future uses. Since I have never used Command Prompt before and I also searched online but most of them cannot answer.

谁能在这里展示解决方案?谢谢.

Can anyone show the solution here? Thanks.

推荐答案

您可以使用 %save:

用法:

%save [选项] 文件名 n1-n2 n3-n4 ... n5 .. n6 ...选项:

%save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... Options:

-r:使用原始"输入.默认情况下,使用已处理"历史记录,以便将魔法在其转换后的版本中加载到有效的 Python 中.如果给出此选项,则使用作为命令行输入的原始输入.

-r: use ‘raw’ input. By default, the ‘processed’ history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead.

-f:强制覆盖.如果文件存在,%save 将提示覆盖,除非给出 -f.

-f: force overwrite. If file exists, %save will prompt for overwrite unless -f is given.

-a:附加到文件而不是覆盖它.

-a: append to the file instead of overwriting it.

此函数对输入范围使用与 %history 相同的语法,然后将行保存到您指定的文件名.

This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.

如果您自己不这样做,它会在文件中添加一个.py"扩展名,并在覆盖现有文件之前要求确认.

It adds a ‘.py’ extension to the file if you don’t do so yourself, and it asks for confirmation before overwriting existing files.

如果使用 -r 选项,默认扩展名是 .ipy.

If -r option is used, the default extension is .ipy.

In [1]: def foo():
   ...:     print("hello world")
   ...:     

In [2]: %save my_code 1
The following commands were written to file `my_code.py`:
def foo():
    print("hello world")


In [3]: cat my_code.py
# coding: utf-8
def foo():
    print("hello world")

这篇关于如何将命令提示符中的 Python 编码保存为文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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