Wednesday, May 1, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 4741  / 2 Years ago, sun, july 17, 2022, 1:08:38

I am trying to execute very basic Python code containing error handling as a Bash script, but while the code seems to run OK in Python, the code generates problems when executed under Bash.



#!/usr/bin/python 
x = input('Enter your number: ')
try:
x = float(x)
print('Your number multiplied by 2 is: ', x*2)
except ValueError:
print('not a valid choice')
x == 0


This is the error report from Bash:



Enter your number:  -p Traceback (most recent call last):
File "cycle.py", line 3, in <module>
x=input('Enter your number: ')
File "<string>", line 1, in <module>
NameError: name 'p' is not defined


As I understand the input error had to be handled by Python first and then it would return 0 exit status to Bash, but apparently this is not the case?




  1. Is my code all right?

  2. Is there a way to force Python to handle the error first without evoking Bash?

  3. Is there any other critical pitfalls when running Python programs (presumably correctly written) as Bash scripts?


More From » bash

 Answers
0

You write your code in Python 3 (looking at "print"), but the shebang suggests Python 2. Change the shebang to



#!/usr/bin/env python3


and run it by:



python3 /path/to/script.py


and it will run fine :)



Explanation:



As hinted in Florian Diesch' comment, input() has changed in Python 3:



In Python 2, input() tries to use the input as a Python expression (like eval()), while in Python 3, input() replaces the raw_input() from Python 2.


[#24606] Sunday, July 17, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ionash

Total Points: 214
Total Questions: 111
Total Answers: 116

Location: Sudan
Member since Thu, May 7, 2020
4 Years ago
;