如何将float argv参数传递到另一个脚本?

时间:2019-06-27 23:00:21

标签: python ubuntu-16.04

我正在尝试在终端中使用test运行一个名为python test的简单脚本,以便调用另外两个脚本。

这是我正在运行的脚本

#!/usr/bin/env python

import sys
import rospy
import subprocess
import time

from geometry_msgs.msg import Twist
from std_msgs.msg import Empty

subprocess.call("./takeoff_sim")

time.sleep(2)

subprocess.call("./forward_sim" + sys.argv[5.0] + sys.argv[2.0])

但是我遇到了以下错误:

Traceback (most recent call last):
  File "test", line 15, in <module>
    subprocess.call(["./forward_sim"] + sys.argv[5.0] + sys.argv[2.0])
TypeError: list indices must be integers, not float

在这种情况下,两个参数都需要浮点数,因此,我不能仅将它们更改为int 0.5应该是第一个参数,2.0应该是第二个参数。这是forward_sim脚本:

#!/usr/bin/env python
import sys
import rospy
from geometry_msgs.msg import Twist

def commander(speed, time):
    movement_publisher = rospy.Publisher('cmd_vel', Twist , queue_size=10)
    rospy.init_node("bebop_commander") #Use log_level=rospy.DEBUG to see debug messages
    rate = rospy.Rate(20) # 20hz
    counter = 0.0
    movement_cmd = Twist()

    while not rospy.is_shutdown():
        movement_cmd.linear.x = speed
        movement_cmd.linear.y = 0
        movement_cmd.linear.z = 0
        movement_cmd.angular.x = 0
        movement_cmd.angular.y = 0
        movement_cmd.angular.z = 0
        rospy.logdebug("Publishing")
    counter += 0.05
        movement_publisher.publish(movement_cmd)
        rate.sleep()
        if counter >= time:
        break

if __name__ == '__main__':
    speed = float(sys.argv[0])
    time = float(sys.argv[1])


rospy.logdebug("Adelante") # Use rospy.logdebug() for debug messages.
print("Adelante")

if speed > 0:
        rospy.logdebug("Velocidad = %s m/s", speed)
    print("Velocidad =",speed," m/s",)
else:
        raise ValueError("Falta parametro de velocidad o el valor es incorrecto")

if time > 0 :
        rospy.logdebug("Tiempo = %s s", time)
    print("Tiempo =" ,time, " s")
else:
        raise ValueError("Falta parametro de tiempo o el valor es incorrecto")

try:
    commander(speed, time)
except rospy.ROSInterruptException:
    pass

1 个答案:

答案 0 :(得分:2)

sys.argv仅用于接收参数。要将值作为参数传递给另一个脚本,只需将它们转换为字符串并将其直接添加到命令行即可。

subprocess.call(["./forward_sim", str(5.0), str(2.0)])

其他脚本收到它们时,需要将每个字符串转换回浮点数:

# This is forward_sim

arg1 = float(sys.argv[1])
arg2 = float(sys.argv[2])

请注意,sys.argv[0]是脚本本身的名称,而不是第一个参数。