标签归档:nameerror

NameError:全局名称“ unicode”未定义-在Python 3中

问题:NameError:全局名称“ unicode”未定义-在Python 3中

我正在尝试使用一个名为bidi的Python包。在此程序包(algorithm.py)的模块中,尽管它是程序包的一部分,但仍有一些行会给我带来错误。

以下是这些行:

# utf-8 ? we need unicode
if isinstance(unicode_or_str, unicode):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True

这是错误消息:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    bidi_text = get_display(reshaped_text)
  File "C:\Python33\lib\site-packages\python_bidi-0.3.4-py3.3.egg\bidi\algorithm.py",   line 602, in get_display
    if isinstance(unicode_or_str, unicode):
NameError: global name 'unicode' is not defined

我应该如何重新编写代码的这一部分,使其可以在Python3中使用?另外,如果有人在Python 3中使用了bidi软件包,请让我知道他们是否发现了类似的问题。我感谢您的帮助。

I am trying to use a Python package called bidi. In a module in this package (algorithm.py) there are some lines that give me error, although it is part of the package.

Here are the lines:

# utf-8 ? we need unicode
if isinstance(unicode_or_str, unicode):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True

and here is the error message:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    bidi_text = get_display(reshaped_text)
  File "C:\Python33\lib\site-packages\python_bidi-0.3.4-py3.3.egg\bidi\algorithm.py",   line 602, in get_display
    if isinstance(unicode_or_str, unicode):
NameError: global name 'unicode' is not defined

How should I re-write this part of the code so it works in Python3? Also if anyone have used bidi package with Python 3 please let me know if they have found similar problems or not. I appreciate your help.


回答 0

Python 3将unicode类型重命名为str,旧str类型已替换为bytes

if isinstance(unicode_or_str, str):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True

您可能需要阅读Python 3 porting HOWTO以获得更多此类详细信息。还有Lennart Regebro的“ 移植到Python 3:深入指南”,可免费在线获得。

最后但并非最不重要的一点是,您可以尝试使用该2to3工具查看如何为您翻译代码。

Python 3 renamed the unicode type to str, the old str type has been replaced by bytes.

if isinstance(unicode_or_str, str):
    text = unicode_or_str
    decoded = False
else:
    text = unicode_or_str.decode(encoding)
    decoded = True

You may want to read the Python 3 porting HOWTO for more such details. There is also Lennart Regebro’s Porting to Python 3: An in-depth guide, free online.

Last but not least, you could just try to use the 2to3 tool to see how that translates the code for you.


回答 1

如果您需要让脚本像我一样继续在python2和3上工作,这可能会对某人有所帮助

import sys
if sys.version_info[0] >= 3:
    unicode = str

然后可以例如

foo = unicode.lower(foo)

If you need to have the script keep working on python2 and 3 as I did, this might help someone

import sys
if sys.version_info[0] >= 3:
    unicode = str

and can then just do for example

foo = unicode.lower(foo)

回答 2

您可以使用6个库同时支持Python 2和3:

import six
if isinstance(value, six.string_types):
    handle_string(value)

You can use the six library to support both Python 2 and 3:

import six
if isinstance(value, six.string_types):
    handle_string(value)

回答 3

希望您使用的是Python 3,默认情况下Str是unicode,所以请Unicode用String Str函数替换函数。

if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False

Hope you are using Python 3 , Str are unicode by default, so please Replace Unicode function with String Str function.

if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False

python NameError:全局名称’__file__’未定义

问题:python NameError:全局名称’__file__’未定义

当我在python 2.7中运行此代码时,出现此错误:

Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
    long_description = read('README.txt'),
  File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 19, in read
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
NameError: global name '__file__' is not defined

代码是:

import os
from setuptools import setup


def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()


setup(name="pyutilib.subprocess",
    version='3.5.4',
    maintainer='William E. Hart',
    maintainer_email='wehart@sandia.gov',
    url = 'https://software.sandia.gov/svn/public/pyutilib/pyutilib.subprocess',
    license = 'BSD',
    platforms = ["any"],
    description = 'PyUtilib utilites for managing subprocesses.',
    long_description = read('README.txt'),
    classifiers = [
        'Development Status :: 4 - Beta',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Unix Shell',
        'Topic :: Scientific/Engineering :: Mathematics',
        'Topic :: Software Development :: Libraries :: Python Modules'],
      packages=['pyutilib', 'pyutilib.subprocess', 'pyutilib.subprocess.tests'],
      keywords=['utility'],
      namespace_packages=['pyutilib'],
      install_requires=['pyutilib.common', 'pyutilib.services']
      )

When I run this code in python 2.7, I get this error:

Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
    long_description = read('README.txt'),
  File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 19, in read
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
NameError: global name '__file__' is not defined

code is:

import os
from setuptools import setup


def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()


setup(name="pyutilib.subprocess",
    version='3.5.4',
    maintainer='William E. Hart',
    maintainer_email='wehart@sandia.gov',
    url = 'https://software.sandia.gov/svn/public/pyutilib/pyutilib.subprocess',
    license = 'BSD',
    platforms = ["any"],
    description = 'PyUtilib utilites for managing subprocesses.',
    long_description = read('README.txt'),
    classifiers = [
        'Development Status :: 4 - Beta',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Unix Shell',
        'Topic :: Scientific/Engineering :: Mathematics',
        'Topic :: Software Development :: Libraries :: Python Modules'],
      packages=['pyutilib', 'pyutilib.subprocess', 'pyutilib.subprocess.tests'],
      keywords=['utility'],
      namespace_packages=['pyutilib'],
      install_requires=['pyutilib.common', 'pyutilib.services']
      )

回答 0

当您将此行添加os.path.join(os.path.dirname(__file__))到python交互式shell中时,会出现此错误。

Python Shell不会检测到其中的当前文件路径,__file__并且与filepath您添加此行的位置有关

所以,你应该写这条线os.path.join(os.path.dirname(__file__))file.py。然后运行python file.py,它起作用,因为它需要您的文件路径。

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.

Python Shell doesn’t detect current file path in __file__ and it’s related to your filepath in which you added this line

So you should write this line os.path.join(os.path.dirname(__file__)) in file.py. and then run python file.py, It works because it takes your filepath.


回答 1

我在PyInstaller和Py2exe上遇到了同样的问题,所以我遇到了来自cx-freeze的FAQ上的解决方案。

从控制台或作为应用程序使用脚本时,以下功能将为您提供“执行路径”,而不是“实际文件路径”:

print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))

资料来源:http :
//cx-freeze.readthedocs.org/en/latest/faq.html

您的旧行(最初的问题):

def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

使用以下代码段替换您的代码行。

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

使用以上代码,您可以将应用程序添加到os的路径中,可以在任何地方执行它,而不会出现应用程序无法找到其数据/配置文件的问题。

使用python测试:

  • 3.3.4
  • 2.7.13

I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.

When using your script from the console or as an application, the functions hereunder will deliver you the “execution path”, not the “actual file path”:

print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))

Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html

Your old line (initial question):

def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

Substitute your line of code with the following snippet.

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it’s data/configuration files.

Tested with python:

  • 3.3.4
  • 2.7.13

回答 2

如下更改代码!这个对我有用。`

os.path.dirname(os.path.abspath("__file__"))

change your codes as follows! it works for me. `

os.path.dirname(os.path.abspath("__file__"))

回答 3

我遇到了__file__无法正常工作的情况。但是到目前为止,以下内容并没有使我失望:

import inspect
src_file_path = inspect.getfile(lambda: None)

这是最接近C语言的Python类似物 __FILE__

Python的行为与__file__C的行为大不相同__FILE__。C版本将为您提供源文件的原始路径。这对于记录错误和了解哪个源文件存在错误很有用。

Python __file__仅为您提供当前正在执行的文件的名称,这在日志输出中可能不是很有用。

I’ve run into cases where __file__ doesn’t work as expected. But the following hasn’t failed me so far:

import inspect
src_file_path = inspect.getfile(lambda: None)

This is the closest thing to a Python analog to C’s __FILE__.

The behavior of Python’s __file__ is much different than C’s __FILE__. The C version will give you the original path of the source file. This is useful in logging errors and knowing which source file has the bug.

Python’s __file__ only gives you the name of the currently executing file, which may not be very useful in log output.


回答 4

您正在使用交互式解释器吗?您可以使用

sys.argv[0]

您应该阅读:如何获取Python中当前已执行文件的路径?

Are you using the interactive interpreter? You can use

sys.argv[0]

You should read: How do I get the path of the current executed file in Python?


回答 5

我通过将文件视为字符串来解决它,即放在"__file__"(加上引号!)而不是__file__

这对我来说很好:

wk_dir = os.path.dirname(os.path.realpath('__file__'))

I solved it by treating file as a string, i.e. put "__file__" (together with the quotes!) instead of __file__

This works fine for me:

wk_dir = os.path.dirname(os.path.realpath('__file__'))

回答 6

如果你正在寻找的是让你的当前工作目录os.getcwd()会给你同样的事情,os.path.dirname(__file__)只要你有没有在你的代码的其他地方改变工作目录。 os.getcwd()也可以在交互模式下使用。

所以 os.path.join(os.path.dirname(__file__)) 变成 os.path.join(os.getcwd())

If all you are looking for is to get your current working directory os.getcwd() will give you the same thing as os.path.dirname(__file__) as long as you have not changed the working directory elsewhere in your code. os.getcwd() also works in interactive mode.

So os.path.join(os.path.dirname(__file__)) becomes os.path.join(os.getcwd())


回答 7

如果您是从python shell运行命令,则将获得以下信息:

>>> __file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

您需要通过将其作为参数传递给python命令来直接执行文件:

$ python somefile.py

在您的情况下, python setup.py install

You will get this if you are running the commands from the python shell:

>>> __file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

You need to execute the file directly, by passing it in as an argument to the python command:

$ python somefile.py

In your case, it should really be python setup.py install


回答 8

您可以使用以下方法

import os
if '__file__' in vars():
    wk_dir = os.path.dirname(os.path.realpath('__file__'))
else:
    print('We are running the script interactively')

注意这里使用字符串'__file__'确实的是指实际变量__file__。您当然可以自己测试一下。

该解决方案的额外好处是,您可以部分交互地运行脚本(例如,测试/开发脚本),并且可以通过命令行运行该脚本,从而具有灵活性

What you can do is to use the following

import os
if '__file__' in vars():
    wk_dir = os.path.dirname(os.path.realpath('__file__'))
else:
    print('We are running the script interactively')

Note here that using the string '__file__' does indeed refer to the actual variable __file__. You can test this out yourself of course..

The added bonus of this solution is the flexibilty when you are running a script partly interactively (e.g. to test/develop it), and can run it via the commandline


回答 9

如果您通过命令行执行文件,则可以使用此hack

import traceback

def get_this_filename():
    try:
        raise NotImplementedError("No error")
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filename = traceback.extract_tb(exc_traceback)[-1].filename
    return filename

这在UnrealEnginePython控制台中对我有用, py.exec myfile.py

If you’re exec’ing a file via command line, you can use this hack

import traceback

def get_this_filename():
    try:
        raise NotImplementedError("No error")
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filename = traceback.extract_tb(exc_traceback)[-1].filename
    return filename

This worked for me in the UnrealEnginePython console, calling py.exec myfile.py


回答 10

我在Jupyter笔记本电脑中遇到了同样的问题。当我使用’os.path.split(os.path.realpath(file))’时,笔记本抛出了错误。

因此,我使用了“ 文件 ”。效果很好。

I had the same problem in Jupyter notebook. While I used ‘os.path.split(os.path.realpath(file))’ , the notebook was throwing an error.

I thus used ‘file‘. It worked perfectly.


回答 11

我有完全相同的问题,并可能使用相同的教程。函数定义:

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

是越野车,因为os.path.dirname(__file__)不会返回您需要的东西。尝试替换os.path.dirname(__file__)os.path.dirname(os.path.abspath(__file__))

def read(*rnames):
    return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()

我刚刚发布了Andrew消息,当前文档中的代码段不起作用,希望它会得到纠正。

I’m having exacty the same problem and using probably the same tutorial. The function definition:

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

is buggy, since os.path.dirname(__file__) will not return what you need. Try replacing os.path.dirname(__file__) with os.path.dirname(os.path.abspath(__file__)):

def read(*rnames):
    return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()

I’ve just posted Andrew that the code snippet in current docs don’t work, hopefully, it’ll be corrected.


NameError:名称“ self”未定义

问题:NameError:名称“ self”未定义

为什么这样的结构

class A:
    def __init__(self, a):
        self.a = a

    def p(self, b=self.a):
        print b

给一个错误NameError: name 'self' is not defined

Why such structure

class A:
    def __init__(self, a):
        self.a = a

    def p(self, b=self.a):
        print b

gives an error NameError: name 'self' is not defined?


回答 0

默认参数值在函数定义时评估,但self仅在函数调用时可用。因此,参数列表中的参数不能相互引用。

将参数默认为默认值None并在代码中为此添加测试是一种常见的模式:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It’s a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

回答 1

对于您还希望将“ b”设置为“无”的情况:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

For cases where you also wish to have the option of setting ‘b’ to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

回答 2

如果您通过Google到达这里,请确保检查是否已将self作为类函数的第一个参数。特别是如果您尝试在函数中引用该对象的值。

def foo():
    print(self.bar)

> NameError:名称“ self”未定义

def foo(self):
    print(self.bar)

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name ‘self’ is not defined

def foo(self):
    print(self.bar)

input()错误-NameError:名称“ …”未定义

问题:input()错误-NameError:名称“ …”未定义

尝试运行此简单脚本时出现错误:

input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

假设我输入“花花公子”,我得到的错误是:

line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <module>
NameError: name 'dude' is not defined

我正在使用python 2.7运行这些脚本。

I am getting an error when I try to run this simple script:

input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

Let’s say I type in “dude”, the error I am getting is:

line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <module>
NameError: name 'dude' is not defined

I am running these scripts with Python 2.7.


回答 0

TL; DR

inputPython 2.7中的函数,将您输入的内容评估为Python表达式。如果您只是想读取字符串,请使用raw_inputPython 2.7中的函数,该函数不会评估读取的字符串。

如果您使用的是Python 3.x,raw_input则已重命名为input。引用Python 3.0发行说明

raw_input()已重命名为input()。也就是说,新input()函数从中读取一行,sys.stdin并删除尾随的换行符来返回它。EOFError如果输入过早终止,它将触发。要获取的旧行为input(),请使用eval(input())


在Python 2.7中,有两个函数可用于接受用户输入。一个是input,另一个是raw_input。您可以想到它们之间的关系如下

input = eval(raw_input)

考虑下面的代码以更好地理解这一点

>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'

input从用户接受一个字符串,并在当前Python上下文中评估该字符串。当我输入dude作为输入时,它将发现dude绑定到该值thefourtheye,因此求值结果变为,thefourtheye并将其分配给input_variable

如果我输入当前python上下文中不存在的其他内容,它将失败NameError

>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'dummy' is not defined

Python 2.7的安全注意事项input

由于评估了任何用户类型,因此也存在安全问题。例如,如果您已经使用加载os了程序中的模块import os,然后用户输入

os.remove("/etc/hosts")

它将由python评估为函数调用表达式,并将执行该函数。如果您以提升的权限执行Python,则/etc/hosts文件将被删除。瞧,这有多危险?

为了演示这一点,让我们尝试input再次执行函数。

>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude

现在,当input("Enter your name: ")执行时,它等待用户输入,并且用户输入是有效的Python函数调用,因此也会被调用。这就是为什么我们Enter your name again:再次看到提示。

因此,您最好使用这样的raw_input功能

input_variable = raw_input("Enter your name: ")

如果需要将结果转换为其他类型,则可以使用适当的函数将所返回的字符串转换为raw_input。例如,要将输入读取为整数,请使用此答案中int所示的函数。

在python 3.x中,只有一个函数可以获取用户输入,该函数称为inputpython 2.7的raw_input

TL;DR

input function in Python 2.7, evaluates whatever your enter, as a Python expression. If you simply want to read strings, then use raw_input function in Python 2.7, which will not evaluate the read strings.

If you are using Python 3.x, raw_input has been renamed to input. Quoting the Python 3.0 release notes,

raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input())


In Python 2.7, there are two functions which can be used to accept user inputs. One is input and the other one is raw_input. You can think of the relation between them as follows

input = eval(raw_input)

Consider the following piece of code to understand this better

>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'

input accepts a string from the user and evaluates the string in the current Python context. When I type dude as input, it finds that dude is bound to the value thefourtheye and so the result of evaluation becomes thefourtheye and that gets assigned to input_variable.

If I enter something else which is not there in the current python context, it will fail will the NameError.

>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'dummy' is not defined

Security considerations with Python 2.7’s input:

Since whatever user types is evaluated, it imposes security issues as well. For example, if you have already loaded os module in your program with import os, and then the user types in

os.remove("/etc/hosts")

this will be evaluated as a function call expression by python and it will be executed. If you are executing Python with elevated privileges, /etc/hosts file will be deleted. See, how dangerous it could be?

To demonstrate this, let’s try to execute input function again.

>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude

Now, when input("Enter your name: ") is executed, it waits for the user input and the user input is a valid Python function invocation and so that is also invoked. That is why we are seeing Enter your name again: prompt again.

So, you are better off with raw_input function, like this

input_variable = raw_input("Enter your name: ")

If you need to convert the result to some other type, then you can use appropriate functions to convert the string returned by raw_input. For example, to read inputs as integers, use the int function, like shown in this answer.

In python 3.x, there is only one function to get user inputs and that is called input, which is equivalent to Python 2.7’s raw_input.


回答 1

您正在运行Python 2,而不是Python3。要在Python 2中运行,请使用raw_input

input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)

You are running Python 2, not Python 3. For this to work in Python 2, use raw_input.

input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)

回答 2

由于您是为Python 3.x编写的,因此您需要以以下内容开始脚本:

#!/usr/bin/env python3

如果您使用:

#!/usr/bin/env python

它将默认为Python2.x。如果没有以开头的内容,它们将放在脚本的第一行(又名shebang)。

如果您的脚本仅以以下内容开头:

#! python

然后,您可以将其更改为:

#! python3

尽管只有一些程序(例如启动器)可以识别这种较短的格式,但这并不是最佳选择。

前两个示例被广泛使用,将有助于确保您的代码在安装了Python的任何计算机上都能正常工作。

Since you are writing for Python 3.x, you’ll want to begin your script with:

#!/usr/bin/env python3

If you use:

#!/usr/bin/env python

It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #! (aka the shebang).

If your scripts just start with:

#! python

Then you can change it to:

#! python3

Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.

The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.


回答 3

您应该使用,raw_input因为您使用的是python-2.7。在input()变量上使用时(例如s = input('Name: '):),它将在Python环境上执行命令,而不会保存您在变量(s)上写的内容,如果未定义写的内容,则会产生错误。

raw_input()会正确保存您在变量上写的内容(例如:)f = raw_input('Name : '),并且不会在Python环境中执行该操作而不会产生任何可能的错误:

input_variable = raw_input('Enter Your Name : ')
print("Your Name Is  : " + (input_variable))

You should use raw_input because you are using python-2.7. When you use input() on a variable (for example: s = input('Name: ')), it will execute the command ON the Python environment without saving what you wrote on the variable (s) and create an error if what you wrote is not defined.

raw_input() will save correctly what you wrote on the variable (for example: f = raw_input('Name : ')), and it will not execute it in the Python environment without creating any possible error:

input_variable = raw_input('Enter Your Name : ')
print("Your Name Is  : " + (input_variable))

回答 4

对于python 3及更高版本

s = raw_input()

如果您要在hackerrank网站上进行在线解决,它将解决pycharm IDE上的问题,然后使用:

s = input()

For python 3 and above

s = raw_input()

it will solve the problem on pycharm IDE if you are solving on online site exactly hackerrank then use:

s = input()

回答 5

您可以这样做:

x = raw_input("enter your name")
print "your name is %s " % x

要么:

x = str(input("enter your name"))
print "your name is %s" % x

You could either do:

x = raw_input("enter your name")
print "your name is %s " % x

or:

x = str(input("enter your name"))
print "your name is %s" % x

回答 6

input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

您必须输入单引号或双引号

Ex:'dude' -> correct

    dude -> not correct
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

You have to enter input in either single or double quotes

Ex:'dude' -> correct

    dude -> not correct

回答 7

我还遇到了一个本应与python 2.7和3.7兼容的模块的问题

我发现解决问题的是导入:

from six.moves import input

这固定了两个口译员的可用性

你可以在这里阅读更多关于六个图书馆的信息

I also encountered this issue with a module that was supposed to be compatible for python 2.7 and 3.7

what i found to fix the issue was importing:

from six.moves import input

this fixed the usability for both interpreters

you can read more about the six library here


回答 8

我们正在使用以下适用于python 2和python 3的内容

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

回答 9

对于可能会遇到此问题的其他任何人,事实证明,即使您#!/usr/bin/env python3在脚本的开头添加了该文件,如果该文件不可执行,也将忽略shebang。

要确定您的文件是否可执行:

  • 运行./filename.py在命令行
  • 如果得到-bash: ./filename.py: Permission denied,请运行chmod a+x filename.py
  • 再跑./filename.py一次

如果您已import sys; print(sys.version)按照Kevin的建议加入,现在您将看到python3正在解释该脚本

For anyone else that may run into this issue, turns out that even if you include #!/usr/bin/env python3 at the beginning of your script, the shebang is ignored if the file isn’t executable.

To determine whether or not your file is executable:

  • run ./filename.py from the command line
  • if you get -bash: ./filename.py: Permission denied, run chmod a+x filename.py
  • run ./filename.py again

If you’ve included import sys; print(sys.version) as Kevin suggested, you’ll now see that the script is being interpreted by python3


回答 10

以前的贡献不错。

import sys; print(sys.version)

def ingreso(nombre):
    print('Hi ', nombre, type(nombre))

def bienvenida(nombre):
    print("Hi "+nombre+", bye ")

nombre = raw_input("Enter your name: ")

ingreso(nombre)
bienvenida(nombre)

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
输入您的姓名:Joe
(“嗨”,“乔”,<类型“ str”>)
嗨乔,再见 

您的名字:Joe
乔

谢谢!

Good contributions the previous ones.

import sys; print(sys.version)

def ingreso(nombre):
    print('Hi ', nombre, type(nombre))

def bienvenida(nombre):
    print("Hi "+nombre+", bye ")

nombre = raw_input("Enter your name: ")

ingreso(nombre)
bienvenida(nombre)

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
Enter your name: Joe
('Hi ', 'Joe', &lttype 'str'&gt)
Hi Joe, bye 

Your name: Joe
Joe

Thanks!


回答 11

有两种方法可以解决这些问题,

  • 第一个很简单,无需更改代码,该代码
    由Python3运行,
    如果您仍然想在python2上运行,那么在运行python脚本后,输入输入时请记住

    1. 如果要输入,string则只需使用“ input go with double-quote”输入即可,它将在python2.7和
    2. 如果您想输入字符,请在输入中使用单引号,例如“您的输入在此处”
    3. 如果您想输入数字而不是问题,只需键入数字
  • 第二种方法是代码更改,
    使用以下导入并与任何版本的python一起运行

    1. from six.moves import input
    2. 在任何导入中使用raw_input()函数代替input()代码中的函数
    3. 使用str()like函数清理代码,str(input())然后将其分配给任何变量

错误提示
未定义名称“ dude”,即python的“ dude”在此处变为变量,并且没有分配任何python定义的类型的值,
因此只能像婴儿一样哭泣,因此如果我们定义“ dude”变量并分配任何值并传递给它,它将起作用,但这不是我们想要的,因为我们不知道用户将输入什么,此外,我们还希望捕获用户输入。

关于这些方法的事实:
input()函数:此函数按原样使用您输入的输入的值和类型,而无需修改其类型。
raw_input() 函数:此函数将您提供的输入明确转换为字符串类型,

注意:
input()方法的漏洞在于,任何人都可以使用变量或方法的名称来访问访问输入值的变量。

There are two ways to fix these issues,

  • 1st is simple without code change that is
    run your script by Python3,
    if you still want to run on python2 then after running your python script, when you are entering the input keep in mind

    1. if you want to enter string then just start typing down with “input goes with double-quote” and it will work in python2.7 and
    2. if you want to enter character then use the input with a single quote like ‘your input goes here’
    3. if you want to enter number not an issue you simply type the number
  • 2nd way is with code changes
    use the below import and run with any version of python

    1. from six.moves import input
    2. Use raw_input() function instead of input() function in your code with any import
    3. sanitise your code with str() function like str(input()) and then assign to any variable

As error implies:
name ‘dude’ is not defined i.e. for python ‘dude’ become variable here and it’s not having any value of python defined type assigned
so only its crying like baby so if we define a ‘dude’ variable and assign any value and pass to it, it will work but that’s not what we want as we don’t know what user will enter and moreover we want to capture the user input.

Fact about these method:
input() function: This function takes the value and type of the input you enter as it is without modifying it type.
raw_input() function: This function explicitly converts the input you give into type string,

Note:
The vulnerability in input() method lies in the fact that the variable accessing the value of input can be accessed by anyone just by using the name of variable or method.


回答 12

您可以更改在IDE中使用的python,如果您已经下载了python 3.x,则切换起来应该不太困难。但是您的脚本可以在python 3.x上正常工作,我只需要更改

print ("your name is" + input_variable)

print ("your name is", input_variable)

因为使用逗号,它会your name is在用户输入的内容与输入内容之间加上空格。AND:如果您使用的是2.7,请使用raw_input代替输入。

You can change which python you’re using with your IDE, if you’ve already downloaded python 3.x it shouldn’t be too hard to switch. But your script works fine on python 3.x, I would just change

print ("your name is" + input_variable)

to

print ("your name is", input_variable)

Because with the comma it prints with a whitespace in between your name is and whatever the user inputted. AND: if you’re using 2.7 just use raw_input instead of input.