This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 months ago.
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.
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
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().
Related
This question already has answers here:
Store output of subprocess.Popen call in a string [duplicate]
(15 answers)
Closed 1 year ago.
So recently I've been working on automating my code for bug bountys but i want to have a overall out put so it shows what it got neatly
(xssstrike is for example here)
website = (input(Fore.GREEN + "enter url/website for this scan: "))
ops = (input(Fore.GREEN + "enter other operators for xxstrike here (with spaces): "))
def xssstrike():
try:
os.chdir("/mnt/usb/xss-strike")
os.system(f"python3 xsstrike.py {ops} -u {website}")
except ValueError:
raise print("oops! there was an error with xss strike!")
i want to put the output from os.system(f"python3 xsstrike.py {ops} -u {website}") into a variable so i can print it later at the end of the code such as
print("<><><> xss strike output results <><><>")
print(xssstrikeoutput)
forgive me if this is simple im fairly new to coding but overall but ive checked everywhere and cant seem to find a answer
variable_name = os.system(f"python3 xsstrike.py {ops} -u {website}")
This will put the required data in variable. You will be able to print it inside this function only. If you want it to print outside the function either return it or declare it as a global function.
You can do this with subprocess.check_output from the the built-in subprocess module
import subprocess
# instead of os.system
xssstrikeoutput_bytes: bytes = subprocess.check_output(f"python3 xsstrike.py {ops} -u {website}", shell=True)
xssstrikeoutput = xssstrikeoutput_bytes.decode("utf-8")
This way, you will be able to see anything that your xssstrike.py prints.
subprocess.check_output documentation
This question already has answers here:
Python Value Error: not enough values to unpack
(4 answers)
Closed 2 years ago.
I'm using Learning Python the Hard Way. In the process of my learning I came across this error. Though I have been trying to debug since yesterday, I couldn't.
This is my code:
import sys
from sys import argv
script, first, second = argv
print('the script is called:', script)
print('the first variable is:', first)
print('the second vriable is:', second)
print('the third variable is:', third)
The error you're getting means you're trying to deconstruct an iterable (list, tuple) into more values than there are in the actual list. If you were to run
print(argv, len(argv))
You might see that you don't have three variables in argv.
argv shows the parameters you provided while running a script. So for example, if I ran:
python test_args.py
I would only receive: ['test_args.py'] as my argv variable. If I tried providing more parameters, like:
python test_args.py a b
Then my argv would look like: ['test_args.py', 'a', 'b']. Your code is completely dependent on how many parameters are passed when you are running it, so mess around with that as well to get a better sense of what is going on.
I suppose that you are executing the script in this format
python script.py 10 20
The problem is that you are using an extra variable third which is not initialized.
If you really want 3 arguments, then you have to pass three values at execution time as follows.
python script.py 10 20 30
Then change the code as follows.
from sys import argv
script, first, second, third = argv
print('the script is called:', script)
print('the first variable is:', first)
print('the second vriable is:', second)
print('the third variable is:', third)
Thank you
This question already has answers here:
How to get just the return value from a function in Python?
(2 answers)
Closed 3 years ago.
I know this this questions been asked before, but I can't seem to get the answers to work. I'm trying to pass the variable things from one script to another.
test.py
def addstuff(word):
things = word + " good."
return things
test2.py
from test import addstuff
addstuff("random")
stuff = things + "morethings"
Ive also tried importing with
from test import *
things doesn't show up as defined in test2, How can I fix this?
The addstuff("random") does not store the output of your addstuff() function from test.py into any variable, its just discarded.
The things in your test2.py does not mean anything to the program until its not assigned to any variable.
Here's the correct way to do it:
from test import addstuff
things=addstuff("random")
stuff = things + "morethings"
We're assigning the output of addstuff("random") (ie "random good.") to things and then adding "morethings" to it.
This question already has an answer here:
How can I decorate all functions imported from a file?
(1 answer)
Closed 4 years ago.
I'd like to automatically print python statements as they are called in a script while the script runs. Could anybody show a ready-to-use solution?
For example, I may have the following python code.
print "xxx"
myfun()
I'd like print "xxx" and myfun() be printed exactly in the output.
One solution is manually to add a print statement to each function. But this is combersome.
print 'print "xxx"'
print "xxx"
print 'myfun()'
myfun()
The following solutions just can not do so. Please do not mark this question as duplicate.
The solution here will not only print the functions in the current script but also functions in other scripts used in the current scripts. These solutions are not what I need.
How do I print functions as they are called
The following does not do what I need because it does not limit the decoration to the current file. For example, it uses import mymod1; decorate_all_in_module(mymod1, decorator). I don't have a module. I want to print the statements in the current script.
How can I decorate all functions imported from a file?
There is no "ready-to-use" solution to this problem. You are asking for a programming language with different semantics than the Python language: therefore you will either need to write code to get this effect, or use a different language, or both.
That said, for solving your actual problem, I believe simply using a debugger would do what you want: that way you can step over each statement in your program and observe as they are executed.
This question already has answers here:
What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?)
(9 answers)
Closed 7 months ago.
I am working my way through "Learning Python the Hard Way". I am totally stumped on "Exercise 13: parameters, unpacking, variables". I'm using Sublime Text 3 in a Windows 7 environment.
Here is my code:
from sys import argv
script, first, second = argv
print ("The script is called:", script)
print ("Your first variable:", first)
print ("Your second variable:", second)
Now my questions:
Do I put this in the scripts folder and then reference this from another .py file something like...
c:\scripts\python\ex11.py one_thing second_thing another_thing
...or do I use a file in my scripts folder to reference my file in another folder that is holding my .py files?
What is the syntax to point to another file in another folder?
It helps to determine what the arguments vector, or argv actually does. It's reading in what you pass in to it from the command line.
So, this means that this command should work (provided Python is in your path, and you can just execute the file in this manner):
C:\scripts\python\ex11.py one_thing second_thing another_thing
Note that you'll only see one_thing and second_thing come across; the first value is the name of the script.
When using the command line to run programs, arguments can be specified to get the program to run in different ways.
In this example, you will need to open up powershell, run cd c:\scripts\python\, and then python ex11.py one_thing second_thing another_thing