Python 使用带参数的subprocess.call
有关 原则上问题是一样的,我有一个subprocess.system调用Python 使用带参数的subprocess.call,python,command-line,environment-variables,sublimetext3,Python,Command Line,Environment Variables,Sublimetext3,有关 原则上问题是一样的,我有一个subprocess.system调用 ... EDITOR = os.environ.get('EDITOR', 'vim') subprocess.call([EDITOR, tf.name]) ... 其中EDITOR是环境$EDITOR变量,tf.name只是一个文件名 但是,建议将$EDITOR设置为export EDITOR='subl-w',使我的呼叫如下所示: subprocess.call(['subl -w', "somefilename"
...
EDITOR = os.environ.get('EDITOR', 'vim')
subprocess.call([EDITOR, tf.name])
...
其中EDITOR
是环境$EDITOR
变量,tf.name
只是一个文件名
但是,建议将$EDITOR
设置为export EDITOR='subl-w'
,使我的呼叫如下所示:
subprocess.call(['subl -w', "somefilename"])
raceback (most recent call last):
File "/usr/bin/note", line 65, in <module>
storage["notes"][args.name] = writeNote(args.name, storage)
File "/usr/bin/note", line 54, in writeNote
subprocess.call([EDITOR, tf.name])
File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1541, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'subl -w'
它的失败是这样的:
subprocess.call(['subl -w', "somefilename"])
raceback (most recent call last):
File "/usr/bin/note", line 65, in <module>
storage["notes"][args.name] = writeNote(args.name, storage)
File "/usr/bin/note", line 54, in writeNote
subprocess.call([EDITOR, tf.name])
File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1541, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'subl -w'
一个解决办法可能是
args = EDITOR.split(" ")
subprocess.call(args + ["somefilename"])
但我有点担心这样做,因为我不知道$EDITOR
设置为什么,这样做安全吗
处理这种情况的正确方法是什么?您可以使用shlex。它处理unixshell类命令。 例如:
shlex.split(“文件夹\编辑器”)+[“somefilename”]
['folder editor','somefilename']
shlex.split(“editor-arg”)+[“somefilename”]
['editor','-arg',somefilename']
因此,您应该能够直接执行:subprocess.call(shlex.split(EDITOR)+[“somefilename”])
您可以使用shlex。它处理unixshell类命令。
例如:shlex.split(“文件夹\编辑器”)+[“somefilename”]
['folder editor','somefilename']
shlex.split(“editor-arg”)+[“somefilename”]
['editor','-arg',somefilename']
因此,您应该能够直接执行:subprocess.call(shlex.split(EDITOR)+[“somefilename”])
@和lrc No不是重复的,这不是我的问题。我知道如何访问环境variables@andlrc不,不是复制品,这不是我的问题。我知道如何访问环境变量