0

I can't convert a string passed throug command line to a function to float.

I'll explain better. I have this function who takes two arguments, the second one is a float

def function():
   first_param = sys.argv[1]
   second_param = float(sys.argv[2])

Then I have this other function who calls the first one in a software container

def callFunction(first_arg, second_arg):
   cmd = 'docker run --rm -v pathFunction:/home/fenics/shared -w /home/fenics/shared quay.io/fenicsproject/stable "python2 function.py ' + first_arg + str(second_arg)
   process = subprocess.Popen(cmd, shell=True)

When I call:

callFunction("some_string",0.02)

it returns me an error in function at the line at whick I try the conversione to float saying: could not convert string to float : shell

UPDATE I've found that the problem is that the first string I'm passing is a path with some spaces in it. Something like: some_string = C:\blabla\my directory\file.txt" with a space between 'my' and 'directory'. I can't change the path, do you know how could I fix it?

SnowyNe
  • 31
  • 2
  • 10
  • 1
    Shouldn't that last line be `process = subprocess.Popen(cmd1, shell=True)`? – tenfishsticks Mar 02 '18 at 19:59
  • At the end of your `cmd`, `+ first_arg + str(second_arg)` should probably have a space between the args, right? I imagine you want `some_string 0.02` instead of `some_string0.02`. – 0x5453 Mar 02 '18 at 20:04

2 Answers2

3
cmd = 'docker run --rm -v pathFunction:/home/fenics/shared -w /home/fenics/shared quay.io/fenicsproject/stable "python2 function.py ' + first_arg + str(second_arg)

You're missing a space between first and second arg. It should be:

cmd = 'docker run --rm -v pathFunction:/home/fenics/shared -w /home/fenics/shared quay.io/fenicsproject/stable "python2 function.py ' + first_arg + ' ' + str(second_arg)

edit

as pointed out, you're also missing a ". Here's the way it should be

cmd = 'docker run --rm -v pathFunction:/home/fenics/shared -w /home/fenics/shared quay.io/fenicsproject/stable "python2 function.py ' + first_arg + ' ' + str(second_arg) + '"'
Maciej Kozik
  • 176
  • 2
  • 8
  • And maybe a closing `"`, too? – Robᵩ Mar 02 '18 at 20:05
  • The space was not the problem, I've just forgotten to write it here. – SnowyNe Mar 02 '18 at 20:14
  • I've found the problem. The first string I'm passing is a path that has some spaces in it (some directory with names like 'my directory'), so the path is splitted throgh the argv. Do you know how could I fix it? – SnowyNe Mar 02 '18 at 20:15
  • 1
    Escape spaces with \ character. See here: https://stackoverflow.com/questions/12902227/how-to-input-a-path-with-a-white-space – Maciej Kozik Mar 02 '18 at 20:17
0

Change sys.argv[1] to sys.argv[0] and sys.argv[1] to sys.argv[2]

def function():
   first_param = sys.argv[0]
   second_param = float(sys.argv[1])

argument indices start from 0, not from 1.

Check tutorial.tutorial

Morse
  • 8,258
  • 7
  • 39
  • 64