简体   繁体   English

使用raw_input代替python3中的输入

[英]use raw_input instead of input in python3

I am in the habit of using raw_input(...) for certain debugging. 我习惯于使用raw_input(...)进行某些调试。 However, in python3 this has changed to input(...) . 但是,在python3中,它已更改为input(...) Is there a way to define an alias at the top of my project, such as: 有没有一种方法可以在我的项目顶部定义别名,例如:

# __init__.py
raw_input = input

I tried the above, but it only worked in the file I added it to, and not any other files in that directory. 我尝试了上面的方法,但是它只能在我添加到的文件中使用,而不能在该目录中的任何其他文件中使用。 I'd like this to work basically in every file within my python repository. 我希望这基本上可以在python信息库中的每个文件中工作。

You can define all aliases in a separate file (eg aliases.py ) then import said file where needed (ie import aliases ). 您可以在单独的文件中定义所有别名(例如aliases.py ),然后在需要时导入该文件(即import aliases )。

The con with this method that you'll be referencing the alias through aliases.alias unless you make the import stricter (ie from aliases import raw_input ) or if you don't care about avoiding a wildcard import (ie from aliases import * ). 这种方法的aliases.alias除非您使导入更加严格(例如, from aliases import raw_input ),或者如果您不关心避免通配符导入(例如, from aliases import * ),则将通过aliases.alias引用别名。

Additionally, if you don't mind another import in the aliases file you can use the builtins namespace: 此外,如果您不介意别名文件中的其他导入,则可以使用内建名称空间:

import builtins

builtins.raw_input = input

You still have to define all aliases separate file (eg aliases.py ) then import said file where needed (ie import aliases ) but the advantage of using the builtins namespace is that you can use that import exactly as given. 您仍然必须定义所有别名单独的文件(例如aliases.py ),然后在需要的地方导入该文件(即import aliases ),但是使用内建命名空间的优点是可以完全按照给定的方式使用该导入。

You can do it by creating a module for creating the renaming function and then importing it to every file you want to like this: 您可以通过创建用于创建重命名功能的模块,然后将其导入到您想要的每个文件中来做到这一点:

First the module function declaration in alias.py 首先在alias.py中声明模块功能

def raw_input(a):
    return input(a)

Secondly, import to another file: 其次,导入到另一个文件:

from alias import raw_input
x = raw_input("hello world")
print(x)

Sadly, you will have to make the import of the module to every file you want to use the renamed function. 不幸的是,您将必须将模块导入到要使用重命名功能的每个文件中。

Hope it works for you! 希望这对你有用!

Put this at the top, and you will get exactly what you want. 将其放在顶部,您将得到您想要的。

import builtins
builtins.raw_input = builtins.input

It is guaranteed to work, but generally considered a bad practice (everybody will be confused with where is that raw_input defined) 它可以保证正常工作,但通常被认为是不好的做法(每个人都会将raw_input定义在何处感到困惑)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM