输入函数在python脚本中不起作用

我是 python 新手,在执行我的输入代码时遇到问题。我的代码如下:

userInput = input("Hi, What is your name? ") 
print("Welcome {0}, Nice to meet you!".format(userInput))

现在的问题是它在 PyCharm 2020 中运行得非常好,但是当我尝试在 Ubuntu 20.04 的终端中运行它时,它返回以下错误:

./userIO.py: line 7: syntax error near unexpected token `('
./userIO.py: line 7: `userInput = input("Hi, What is your name? ")'

我想知道原因可能是什么。你能帮我找出导致问题的原因吗?

stack overflow Input function not working in python script
原文答案
author avatar

接受的答案

When running scripts (e.g. by doing ./script at a command line), Linux uses a special line known as a shebang line to figure out what program is used to run the script. For example, #!/bin/bash for Bash scripts, or #!/usr/bin/env python3 for Python scripts.

If there is no shebang line, Bash will default to running the script in Bash (i.e. as a shell script). Since your script is not a shell script, you get a bunch of errors from Bash attempting to interpret your Python code as a shell script.

To fix this, you need a shebang line, which must be the first line of your script. For a Python 3 script, you may use #!/usr/bin/env python3, e.g. as follows:

#!/usr/bin/env python3
userInput = input("Hi, What is your name? ") 
...

Alternatively, you can fix this by explicitly running your script with the Python interpreter, e.g. python3 script.py.


答案:

作者头像

Thanks to all friends especially nneonneo I can solve my problem in either of the two ways as below:

  1. If running it as a python script without using a shebang (so that the OS can understand how to run it), I can run the script correctly by typing:

      me@linuxbox $> python3 userIO.py
    
  2. If I like to be able to run the script by just typing ./userIO.py, then nneonneo's solution is the best.
    So to find the correct address to my python interpreter I typed: which python3 In my terminal and applied the terminal's return value (in my case it was: /usr/bin/python3) to the beginning of the file's contents as: #!/usr/bin/python3, so that I can now execute the file more easily.

作者头像

You can change your second line of code with:

print(f"Welcome {userInput}, Nice to meet you!")

This reduces number of columns in your code.