问题
I am working on a script that opens media files in VLC Media Player with one of the os.exec*
methods. I am using Python v3.6 on Windows 10.
VLC opens with an error stating that the file cannot be opened, however, the path to the file is also wrong. It shows the file's path starting with my home directory followed by the last portion of the file name separated by a space.
Example:
- I have a video at the path
D:\videos\SuperCoolVideo - Part1.mp4
- VLC attempts to open this video at the path
C:\Users\user\Part1.mp4
instead
The code I am using is as follows:
import os
MEDIA_PLAYER = 'C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe'
video = 'D:\\videos\\SuperCoolVideo - Part1.mp4'
os.execv(MEDIA_PLAYER, [video]) # or os.execl(MEDIA_PLAYER, video)
The error from VLC:
Your input can't be opened:
VLC is unable to open the MRL 'fd://0'. Check the log for details.
Your input can't be opened:
VLC is unable to open the MRL 'file:///C:/Users/user/Part1.mp4'. Check the log for details.
I think (but am not entirely sure) this is because I must define the path of the video or escape the path properly, but I have been unsuccessful in my research on how to handle passing the path properly to VLC.
I have also tried using os.system()
to no avail. I get the following error message:
The filename, directory name, or volume label syntax is incorrect.
* NOTE: I should add that I cannot use subprocess.call('path\to\vlc.exe')
because I need the script to end immediately after VLC is opened. Using subprocess.call()
causes the script to remain running until I close VLC.
回答1:
I got it working properly thanks to the help of Hans Lehnert and Charles Duffy in the question's comments above. Two changes were necessary.
- On Windows, it is necessary to wrap quotes around any arguments that may contain spaces passed to
os.execv
. However, this can be harmful on UNIX-based systems, so do not bother if your are using one. Examples →'"'+path+'"'
or'"{}"'.format(path)
- The first argument must, once again, be your executing process. I will just quote Charles' comment as he explained it well.
Windows is its own very odd bird, but on UNIX-like operating systems, your list starts at
argv[0]
, so if you want the argument to beargv[1]
, you'd need to useos.execv(MEDIA_PLAYER, [MEDIA_PLAYER, video])
."
Solution
So together, I opened files properly in VLC by wrapping arguments in quotes and passing the executable as the first argument in os.execv
:
os.execv(MEDIA_PLAYER, ['"'+MEDIA_PLAYER+'"', '"'+video+'"'])
来源:https://stackoverflow.com/questions/51201534/cannot-open-file-properly-in-vlc-with-pythons-os-execv-or-os-execl-on-windows