原则上的问题是一样的,我有一个subprocess.system调用
...
EDITOR = os.environ.get('EDITOR', 'vim')
subprocess.call([EDITOR, tf.name])
...
EDITOR
是环境$EDITOR
变量,tf.name
只是一个文件名。
但是,sublime text建议将$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"])
解决方法可能是
args = EDITOR.split(" ")
subprocess.call(args + ["somefilename"])
但是我有点担心这样做,因为我不知道$EDITOR
设置的是什么,这样做是否安全?
处理此案件的正确方法是什么?
答案 0 :(得分:4)
你可以使用shlex。它负责UNIX shell之类的命令。
例如:
>>> shlex.split( "folder\ editor" ) + ["somefilename"]
['folder editor', 'somefilename']
>>> shlex.split( "editor -arg" ) + ["somefilename"]
['editor', '-arg', 'somefilename']
所以你应该能够直接做到:
subprocess.call( shlex.split(EDITOR) + ["somefilename"] )