p1.py
import sys
def sum(x1, x2):
return (x1 x2)
x0 = sys.argv[1]
x1 = sys.argv[2]
x2 = sys.argv[3]
print("user is:" x0)
print(x1)
print(x2)
print(sum(float(x1), float(x2)))
print("hello world")
p2.py
import os
import sys
paraA = sys.argv[0]
paraB = sys.argv[1]
paraC = sys.argv[2]
if __name__ == '__main__':
os.system("python p1.py %s %f %f" % (paraA, paraB, paraC))
I run the code with:
python p2.py 3 6
and the error occur:
TypeError: must be real number, not str
Why is that? I want to transmit the name of p2
to p1.name
is str not number. Why does the error occur?
CodePudding user response:
Error lies in this line;
os.system("python p1.py %s %f %f" % (paraA, paraB, paraC))
You are not converting the last two into float;
os.system("python p1.py %s %f %f" % (paraA, float(paraB), float(paraC)))
CodePudding user response:
sys.argv always give you "string", so this line will cause error when you cast a "string"(paraB,paraC) to "%f", which expect a "float".
os.system("python p1.py %s %f %f" % (paraA, paraB, paraC))
And in your case, instead of using "float(paraB)" in "p2.py", I suggest keeping them as string and make them float in p1.py, which your code already did that. This way you cause less trouble as float(1) will print "1.000000" with 6 zero as default.
p2.py
os.system("python p1.py %s %s %s" % (paraA, paraB, paraC))
p1.py
...
x1 = sys.argv[2]
x2 = sys.argv[3]
print(sum(float(x1), float(x2)))
...
CodePudding user response:
sys.argv values are considered as string.
Do this :
paraB = float(sys.argv[1])
paraC = float(sys.argv[2])
Hope it will help you