Assign a value to a variable via terminal?

4 posts
by woodchop146 » Fri Jun 14, 2013 10:32 pm
Hello, I am met with a problem.
I have forged a form of brute force stress test for my Raspberry Pi, but I would like to be able to assign a value for how long it should run for via terminal, instead of having to edit the code.
Code: Select all
def fib(n):
    a, b = 0, 1
    while a < n:
        print a,
        a, b = b, a+b

Basically I would like to be able to type into terminal something like:
Code: Select all
python --fib(100)

Instead of having the preset
Code: Select all

I'm not even sure if it is possible, so any guidance would be brilliant.
User avatar
Posts: 14
Joined: Fri Jun 14, 2013 9:27 pm
by DrMag » Sat Jun 15, 2013 2:11 am
You want to take a look at the sys module. Try this experiment by writing this to a file and running it with whatever arguments you would like:

Code: Select all
#!/usr/bin/env python
import sys

Code: Select all
$ python one two three four
Posts: 61
Joined: Sat Jun 01, 2013 7:59 pm
by woodchop146 » Sat Jun 15, 2013 11:50 am
This is very reassuring that I can input while launching it, but is there a way to split an integer value from the input?
I am currently getting the output of "['', 'pizza'], but this is definitely a step in the right direction.

EDIT: I have figured the last bit out, it was easier than I thought, all I had to do was declare sys.argv as an array.

Code: Select all
import sys
k, m = sys.argv
print k

Thank you very much, DrMag.
User avatar
Posts: 14
Joined: Fri Jun 14, 2013 9:27 pm
by davef21370 » Sat Jun 15, 2013 3:13 pm
That's a workaround but the "standard" way of handling it would be...
Code: Select all
import sys
sys.argv[0] is the name of the program and sys.argv[1] and upwards are the arguments passed to the program.
Hope that clarifies things a little.

Please feel free to tap into my abundant lack of knowledge.
When you're dead you don't know you're dead. It's the same as being stupid.
Apple say. Monkey do.
User avatar
Posts: 824
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded