On Thursday 19 Jan 2017 22:21 CET, Cecil Westerhof wrote: > On Thursday 19 Jan 2017 21:12 CET, MRAB wrote: > >> On 2017-01-19 19:08, Cecil Westerhof wrote: >>> I am writing a python program to start the programs that need to >>> be started after logging in. >>> >>> I have the following imports: >>> from subprocess import check_call, Popen, STDOUT >>> from time import sleep, strftime >>> >>> And use the following code: check_call(tuple('wmctrl -s >>> 10'.split())) log_file = >>> open('Logging/firefox_%T.log'.replace('%T', strftime('%F_%R')), >>> 'w') Popen(tuple('firefox'.split()), stdout = log_file, stderr = >>> STDOUT) >>> >>> The first statement is to go to the correct desktop. >>> >>> Is this a good way to do things, or could I do it in a better way? >>> >> Apart from the other answer, your use of .replace is odd. This >> would be better: >> >> log_file = open('Logging/firefox_%s.log' % strftime('%F_%R'), 'w') > > The reason is that it is ‘generic’ code. In the future instead of > string it will be a variable and only when the variable contains %T > it should be replaced. > > >> Even better would be to use the 'with' statement as well. > > The same here. Not always has the output to be logged and then I > would use NONE for log_file.
I wrote a function for switching to the correct virtual desktop and starting all the commands. I am also using with now: def do_desktop(desktop, commands, seconds_to_wait = 10): desktop_command = ('wmctrl -s ' + desktop).split() check_call(tuple(desktop_command)) for command_arr in commands: command = command_arr[0].split() log_directory = command_arr[1] directory = command_arr[2] if (directory != ''): chdir(directory) if (log_directory == 'NONE'): Popen(tuple(command.split())) else: log_file_name = log_directory.replace('%T', strftime('%F_%R')) with open(log_file_name, 'w') as log_file: Popen(tuple(command), stdout = log_file, stderr = STDOUT) if (directory != ''): set_default_dir() sleep(seconds_to_wait) The function set_default_dir: def set_default_dir(): chdir(expanduser('~')) The example with firefox is then done with: commands = [ ['firefox', 'Logging/firefox_%T.log', ''], ] do_desktop('10', commands, 30) Sometimes a command needs to be executed in a different directory, that is done like: commands = [ ['lein run', 'NONE', 'Clojure/Quotes'], ['xfce4-terminal --maximize --execute screen -S Clojure -c ~/.screenrcClojure', 'NONE', ''], ] do_desktop('6', commands, 30) -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list