Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a number to a python script

I am working in Linux using Ansible.
I am trying to run a script from a playbook, but I need to pass the script a few arguments: a string and 2 numbers. The first number is the number of times I need to retry to run the script, the second number variable is the retry attempt (which comes from a implement retry counter).

cat playbook.yml

---

- name: Increment variable
      ansible.builtin.set_fact:
        attempt_number: "{{ attempt_number | d(0) | int + 1 }}"

- name: Running Script
      command: "{{ my_dir }}/script.py {{ string }} {{ max_retries }} {{ attempt_number | int }}"

The python script looks like this:
cat script.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var1=sys.argv[0]
var2=sys.argv[1]
var3=sys.argv[2]

print "String %s" % var1
print "Num1 %d" % var2
print "Num2 %d" % var3

First I am just trying to check If the variable are being passed to the python script but I am getting this error:

" File "", line 6, in ", "TypeError: %d format: a
number is required, not str"]

What am I doing wrong? How can I change this, so my python script receive all the 3 parameters?

>Solution :

Command line argument values are always strings. If you mean for them to be something else (e.g. int) you have to do that yourself – including any error handling when users pass in the wrong thing:

var1 = sys.argv[0]
var2 = int(sys.argv[1])
var3 = int(sys.argv[2])

try:
    int_arg = int(sys.argv[1])
except ValueError:
    print("invalid command; usage: ...")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading