pass integer variable and string in os.system in python

时间:2016-12-02 05:18:11

标签: python os.system

I am getting SyntaxError: invalid syntax or TypeError: unsupported operand type(s) for +: 'int' and 'str' . Here portnum is integer and the rest are string or

 #!/usr/bin/python
    import getpass
    import sys
    import MySQLdb
    import os    
    os.system('clear')   

    servname = raw_input("What's your server name? ")
    portnum = input("Your instance port number ? ")
    usrname = raw_input("What's your user name? ")
    print(  usrname + " is your username ?")
    passphrase = getpass.getpass("Enter password:")    

    cmdstr="/usr/local/bin/innotop -h " + servname + "-P ", portnum + "-u " +  usrname + "-p " + passphrase

    print(cmdstr)
    os.system("cmdstr")

1 个答案:

答案 0 :(得分:2)

You need a +, not a comma, between each element of a string concatenation, regardless of whether the elements are string literals or named variables. If you use a comma, you create a tuple. If you use nothing, you get a syntax error. Also, be sure to send the integer portnum to str(), so that it can be concatenated as a string.

cmdstr="/usr/local/bin/innotop -h " + servname + "-P " + str(portnum) + "-u " +  usrname + "-p " + passphrase

Also, don't send the literal string 'cmdstr' to os.system(); that's not what you would enter into a command line. You want to send the value that that variable points to, just like you did when you printed it:

os.system(cmdstr)