Passing variables to a subprocess call

后端 未结 6 2037
予麋鹿
予麋鹿 2020-12-04 22:00

I am trying to pass my variables from raw_input to my subprocess command. I am new to Python. Any help would he appreciated.

#!/usr/bin/python
         


        
相关标签:
6条回答
  • 2020-12-04 22:22

    have you tried just using 'xxx{0}'.format(variable) ? see link1 or link2

    subprocess.run(['useradd', '-m', '-g {0}'.format(_primarygroup), '-G {0}'.format(_secondarygroup), '-u {0}'.format(_userid)], capture_output=True)
    

    or

    subprocess.call(['useradd', '-m', '-g {0}'.format(_primarygroup), '-G {0}'.format(_secondarygroup), '-u {0}'.format(_userid)])
    

    just worked fine to me

    0 讨论(0)
  • 2020-12-04 22:24

    You can also use f-strings.

     import subprocess
    
     site = 'google.com'
     subprocess.run(['nslookup', f'{site}'])
    
    0 讨论(0)
  • 2020-12-04 22:25

    Try separating the values with commas:

    subprocess.call(['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, '-u', _userid, _username])
    

    See http://docs.python.org/library/subprocess.html#subprocess.call - It takes an array where the first argument is the program and all other arguments are passed as arguments to the program.

    Also don't forget to check the return value of the function for a zero return code which means "success" unless it doesn't matter for your script if the user was added successfully or not.

    0 讨论(0)
  • You can create the arg string first and then just past this variable to the subprocess.call. For example:

    projects_csv_fn = 'projects_csv_2.csv'
    prjects_json_fn = 'projects.json'
    
    args ='python json_to_csv.py id ' + prjects_json_fn + ' ' + projects_csv_fn
    
    subprocess.call(args, shell=True)
    
    0 讨论(0)
  • 2020-12-04 22:36
    subprocess.call(['useradd', '-m','-g', _primarygroup, '-G', _secondarygroup, '-u', _userid, _username])
    

    Pass a list to subprocess.call

    0 讨论(0)
  • 2020-12-04 22:44

    Try to add commas between your list items:

    subprocess.call(['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, \
                     '-u' ,_userid, _username])
    

    subprocess.call takes the same arguments as subprocess.Popen:

    args should be a string, or a sequence of program arguments.


    Edit

    To turn all your arguments into strings at once you could you a list comprehension:

    args = ['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, \
            '-u' ,_userid, _username]
    str_args = [ str(x) for x in args ]
    
    0 讨论(0)
提交回复
热议问题