4

Related to this question

The question in principle is the same, I have a subprocess.system call

...
EDITOR = os.environ.get('EDITOR', 'vim')
subprocess.call([EDITOR, tf.name])
...

Where EDITOR is the environments $EDITOR variable, tf.name is just a filename.

However, sublime text suggest to set the $EDITOR to export EDITOR='subl -w' Making my call look like this:

subprocess.call(['subl -w', "somefilename"])

And it fails like this:

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'

Of course, it's supposed to look likie this

subprocess.call([subl", "-w" "somefilename"])

A workaround would perhaps be

args = EDITOR.split(" ")
subprocess.call(args + ["somefilename"])

But I'm a little wary of doing this, because I cannot know what $EDITOR is set to, is this safe to do?

What's the proper way to handle this case?

Community
  • 1
  • 1
Azeirah
  • 6,176
  • 6
  • 25
  • 44

1 Answers1

5

You can rather use shlex. It takes care of UNIX shell like commands. For example:
>>> shlex.split( "folder\ editor" ) + ["somefilename"]
['folder editor', 'somefilename']
>>> shlex.split( "editor -arg" ) + ["somefilename"]
['editor', '-arg', 'somefilename']

So you should be able to directly do:
subprocess.call( shlex.split(EDITOR) + ["somefilename"] )

Kunal Grover
  • 190
  • 8