将变量传递给子流程调用
我正在尝试将变量从 raw_input
传递到我的子进程命令。我是Python新手。他将不胜感激任何帮助。
#!/usr/bin/python
import subprocess
print "\nWhat user name"
username = str(raw_input('username: '))
print "\nWhat is the user id"
userid = int(raw_input('Enter user id: '))
print "\nWhat is the user\'s primary group?"
primarygroup = int(raw_input('Enter group: '))
print "\nWhat is the user\'s secondary group?"
secondarygroup = int(raw_input('Enter group: '))
subprocess.call(['useradd' '-m' '-g' _primarygroup '-G' _secondarygroup '-u' _userid _username])
print"\nThe user has been added"
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
import subprocess
print "\nWhat user name"
username = str(raw_input('username: '))
print "\nWhat is the user id"
userid = int(raw_input('Enter user id: '))
print "\nWhat is the user\'s primary group?"
primarygroup = int(raw_input('Enter group: '))
print "\nWhat is the user\'s secondary group?"
secondarygroup = int(raw_input('Enter group: '))
subprocess.call(['useradd' '-m' '-g' _primarygroup '-G' _secondarygroup '-u' _userid _username])
print"\nThe user has been added"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您还可以使用 f 字符串。
You can also use f-strings.
尝试用逗号分隔值:
请参阅 http://docs.python.org/library /subprocess.html#subprocess.call - 它采用一个数组,其中第一个参数是程序,所有其他参数都作为参数传递给程序。
另外,不要忘记检查函数的返回值是否为零返回代码,这意味着“成功”,除非用户添加成功与否对您的脚本来说并不重要。
Try separating the values with commas:
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.
尝试在列表项之间添加逗号:
subprocess.call
采用与subprocess.Popen
:编辑
要将所有参数立即转换为字符串,您可以使用列表理解:
Try to add commas between your list items:
subprocess.call
takes the same arguments assubprocess.Popen
:Edit
To turn all your arguments into strings at once you could you a list comprehension:
您可以先创建 arg 字符串,然后将此变量传递给 subprocess.call。例如:
You can create the arg string first and then just past this variable to the subprocess.call. For example:
将
list
传递给subprocess.call
Pass a
list
tosubprocess.call
您是否尝试过仅使用 'xxx{0}'.format(variable) ?
参见链接1 或 link2
或者
对我来说效果很好
have you tried just using 'xxx{0}'.format(variable) ?
see link1 or link2
or
just worked fine to me