如何在Python中向os.system()语法传递参数?

2 投票
3 回答
6985 浏览
提问于 2025-04-16 19:26
os.system('python manage.py ogrinspect  data/Parking.shp Parking --srid=4326 --mapping --multi > output.txt')

变量 A 的值是 "Parking"。

我该怎么做才能把 A 替换掉所有 os.system() 中的 "Parking" 呢?

3 个回答

0

或者在Python3中

new_text = ''
url = 'www.google.com'
if new_window:
    new_text = '--new-window'
os.system(f'google-chrome-stable {new_text} {url}')
0

如果你只是想在传给 os.system(或者其他任何函数)的字符串中做一些替换,你可以使用字符串插值的方法:

>>> a = "foo"
>>> "abc %s def" % a
'abc foo def'
>>> b = "apples"
>>> "hello %s %s" % (a, b)
'hello foo apples'
>>> "hello %(c)s %(d)s %(c)s" % {'c': a, 'd': b}
'hello foo apples foo'
>>> 

不过,你不能像在一些其他语言(比如 PHP、Ruby 或 TCL)中那样,随便用字符串插值来命名当前作用域里的变量;你必须把变量列出来,并以元组或字典的形式传入。

1

每当你用字符串调用 os.system 时,其实是在启动一个命令行,这样就会自动处理一些命令的扩展,不管你是否想要。这可能会导致一些意想不到的安全问题,特别是当你开始插入变量(尤其是用户提供的变量)时。

与其使用 os.system,不如试试 subprocess.call() 或 subprocess.check_call(),并给它传递一个元组或列表作为参数。当你传递一个列表或元组时,它就不需要启动命令行来处理这些参数。

通过使用列表或元组,你可以轻松地将变量放在参数中。

撰写回答