-2

My situation is as follows: I am testing a Python script where many variables are there, and I want to print out one of the variables controlling from the command line. A toy example is (the script is called toy.py:

import sys

a = 123

print(sys.argv[1])

From the command line I gave: python toy.py a and the output will be a since the a in the command line is taken as string by python. But the expected output is 123, a.k.a I want Python to take the a in the command line as a variable name.

Xiaokang
  • 331
  • 1
  • 11
  • 1
    `print(globals()[sys.argv[1]])`? – Julien Aug 23 '22 at 06:53
  • This is a very, very bad idea - you should never have users interact with your code like that. If that's what you want, have them write a python script and `import toy`. However, if you absolutely must, `eval()` is what you need. Just remember that you hardly ever truly need `eval()`, it's almost always a really bad crutch for a better solution. Look at dictionaries to give users to values you have in code which they need to access by key/label – Grismar Aug 23 '22 at 06:54
  • Could you give more details to explain why you want to do this ? As @Grismar said it seems like a bad idea and there must be better much better solutions – Anto Aug 23 '22 at 06:58
  • Thank you @Grismar for reminding. But no worry, this is just a testing script for my own use. – Xiaokang Aug 23 '22 at 07:09

2 Answers2

1

Use gloabals:

print(globals()[sys.argv[1]])

Ref: https://www.programiz.com/python-programming/methods/built-in/globals

Example:

age = 23

globals()['age'] = 25
print('The age is:', age) // prints: The age is 25
S4RUUL
  • 141
  • 1
  • 3
0

You can access global variables using global() and print them via user input. But this is generally very unsafe and a bad idea. In a commercial program, a website for example, this will lead to a major leak in the system. In other words, you are begging the hackers to penetrate your program.

On the other hand, a very useful solution that I will use in these scenarios is to use a dictionary to hold as many variables as I like, and I will index the dictionary using the command line input.

a = 1
b = 2
c = 3

my_vars = { 'a':a , 'b':b , 'c':c}
print(
      my_vars[ sys.argv[1] ]
     )

There are other solutions using the eval() and exec() functions but those also have the same problem as accessing global().

ARK1375
  • 790
  • 3
  • 19
  • 1
    Using `eval` is even worse as it not only allows hackers to read your source, but even *execute* whatever they please. – Julien Aug 23 '22 at 07:05