Home > Back-end >  How to fix os.system('"%s"' % filename) not launching a file with a space in the
How to fix os.system('"%s"' % filename) not launching a file with a space in the

Time:10-23

I am making a program to work as a stream deck in Python and I store the shortcut names and file paths in a text file. After assigning files to buttons, the names and paths are stored in the file and can be executed. After restarting the program, the shortcuts reappear, but they raise an error when clicking on them, because the file path has a space. I have tried using os.system('"%s"' % filename) but it only works before restarting the program. By not saving the settings the program magically works. Here is the reference code:

import os
from tkinter import filedialog, Tk, Button
import tkinter

root = Tk()

datainfile = []

linecount = 0
with open("config.txt", "r ") as cf:
    for i in cf:
        linecount  = 1
        datainfile.append(i)
configfile = open("config.txt", "a")

def assignname():
    global filename1, name1
    if linecount == 2:
        filename1 = datainfile[0]
        name1 = datainfile[1]
        button1.configure(text=name1, command=Run1)
    else:
        filename1 = filedialog.askopenfilename()
        name1 = input("Name: ")
        configfile.write(filename1 "\n")
        configfile.write(name1  "\n")
        button1.configure(text=name1, command=Run1)


button1 = Button(text="Click me")

def Run1():
    os.system('"%s"' % filename1)

assignname()
button1.pack()
root.mainloop()

After configuring: enter image description here

After restarting and pressing the button: enter image description here

CodePudding user response:

You likely need to remove the newline at the end of the filename:

def Run1():
    os.system('"%s"' % filename1.strip())

Also, please note that in general, you should avoid the use of os.system and use the appropriate function from the subprocess module instead.

  • Related