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"
Related
I have written a python program that needs a first command line argument to run from the Terminal. The program can be used to copy a text to the clipboard when it is run with a certain keyword.
~ python3 mclip.py 'agree'
This use case is just an exercise to understand, how I can run a batch file on macOS (or shell script in macOS terminology).
I have created the following shell script and saved it as mclip.command:
#!/usr/bin/env bash
python3 /Users/Andrea_5K/mclip.py
My idea is to execute my shell script from the spotlight input window, passing the argument 'agree'. How can I do that?
On windows the batch file would look like that (mclip.bat):
#py.exe C:\path_to_my_file\mclip.py %*
#pause
I can press WIN-R and type mclip *argument* to run the program. But how can I do the same on a Mac? I cannot type mclip agree in spotlight, that doesn't work like in WIN-R.
#! python3
# mclip.py - A multi-clipboard program.
TEXT = {
'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""",
'upsell': """Would you consider making this a monthly donation?""",
}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python mclip.py [keyphrase] - copy phrase text')
sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT:
pyperclip.copy(TEXT[keyphrase])
print('Text for ' + keyphrase + ' copied to clipboard.')
else:
print('There is no text for ' + keyphrase)
I can get Spotlight to run a script which:
offers you a dialog box with your three options and
then runs your Python script passing the selected option
But I cannot get Spotlight to pass an option to a Python script directly. If that helps, here's how to do it.
Start Script Editor and enter the following code, save it as an app called mclip:
set theArg to choose from list {"Agree", "Busy", "Upsell"} with title "Chooser Dialog" with prompt "Choose option"
tell application "Terminal"
do shell script "/Users/YOURNAME/mclip.py " & theArg
end tell
Note that adding on run argv at the top still doesn't get you any arguments you add within Spotlight - it just plain doesn't seem to want to pass on any arguments you type in the Spotlight dialog.
Now write a Python script called $HOME/mclip.py:
#!/usr/bin/env python3
import os, sys
# Just write the received parameter into a text file on the Desktop to show how it works
file = os.path.expanduser("~/Desktop/result.txt")
with open(file, 'w') as f:
f.write(sys.argv[1])
And make it executable (just necessary one time) with:
chmod +x $HOME/mclip.py
If you now use Spotlight to run mclip, it will pop up a dialog like this:
You may have to answer security questions the first time you run it - depending on your macOS version.
Note that if all your Python script does is copy some text onto the clipboard, you can do that without Python within the Applescript above using:
set the clipboard to "Some funky text"
Just a detail: python is case sensitive. So, if the keys of the dictionary are lower case, the list values in the apple script ought to be lower case to `:D
Assume the shell script (mapIt.command) is:
#!/usr/bin/env bash
python3 /path/to/my/pythonScript.py $#
The $# is interpreted as a list of command line arguments.
I can run the shell script in the MacOS Terminal like that:
sh mapIt.command Streetname Number City
The command line arguments Streetname Number City are forwarded to the python script.
I wrote a simple extension for vscode, which registers a command, namely comandName.
In my package.json file I have:
"activationEvents": [
"onLanguage:python",
"onCommand:commandName"
]
I meant to execute this command only for Python. To my knowledge, however, the activationEvents in my package.json means that the command would be activated when a Python file is opened or the command is executed. But the command can be executed within any language. I searched the documentation but found no way to execute the command for certain languages.
Is there any way to achieve this target?
I'm afraid this is impossible for now. However you can work around this to avoid any side effects on other files.
If you bind this command to some key combination or to context menu you can use when clause to limit the command to specific types of files.
It will still allow to execute the command from command palette though. To work around this you can just ignore it when being in file other than Python:
vsc.commands.registerTextEditorCommand('testCommand', editor => {
if (editor.document.languageId !== 'python') {
return
}
// command logic
}))
Notice I used registerTextEditorCommand instead of regular command. The difference is that this one requires user to be in text editor context to work which is what you probabl
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"
I am running 2.7 and i am using pyinstaller. My goal is to output a exe and also have it run my other class file. I am also using https://code.google.com/p/dragonfly/ as a framework for voice recognition. I have created another file in the examples direction under dragonfly->examples->text.py . If i run https://code.google.com/p/dragonfly/source/browse/trunk/dragonfly/examples/dragonfly-main.py?spec=svn79&r=79 with my IDE i can say voice commands and it will understand the below file i have created and the other example files that are in the dragonfly examples.
from dragonfly.all import Grammar, CompoundRule, Text, Dictation
import sys
sys.path.append('action.py')
import action
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
print "This works"
spec = "do something computer" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
class AnotherRule(CompoundRule):
spec = "Hi there" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Well, hello"
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.add_rule(AnotherRule()) # Add the command rule to the grammar.
grammar.load()
# Load the grammar.
I noticed in console that it will output
UNKNOWN: valid paths: ['C:\\Users\\user\\workspace\\dragonfly\\dragonfly-0.6.5\\dragonfly\\examples\\action.py',etc..etc...
After i have used pyinstaller the output for that line is
UNKNOWN: valid paths: []
So its not loading the examples because it cannot find them. How can i tell pyinstaller to also load the example files when it is creating an exe? And If it does load the files how can i make sure my exe knows where the files are?
The command i am running for pyinstaller
C:\Python27\pyinstaller-2.0>python pyinstaller.py -p-paths="C:\Users\user\worksp
ace\dragonfly\dragonfly-0.6.5\dragonfly\examples\test.py" "C:\Users\user\workspa
ce\dragonfly\dragonfly-0.6.5\dragonfly\examples\dragonfly-main.py"
If I understand clearly. You have your script and some examples scripts which call your script to show that it is working?
You are missing the point.
Your script supposes to be an end product.
If you want to test functionality do it in development version.
If you want to test exe file do it by another(separated) test script.
Other thing:
Scripts and modules are totally different things.
You are trying to import your script as module and use it in example script.
I suggest you to build main entry point to script (with parameters if you need) as it is meant to be done.
And make other example script which run your script.
Or make a module and build script which uses this module.
Then build this example script to exe file which uses that module and shows it works
PyInstaller can compile one script at once. Forcing it to do unusual things is not needed.
I am new to Python & Eclipse, and having some difficulties understanding how to pass command line argument to script running within Eclipse(Pydev).
The following link explains how to pass command line argument to python script.
To pass command line argument to module argecho.py(code from link above),
#argecho.py
import sys
for arg in sys.argv: 1
print arg
I would need to type into python console
[you#localhost py]$ python argecho.py
argecho.py
or
[you#localhost py]$ python argecho.py abc def
argecho.py
abc
def
How would I pass same arguments to Python script within Eclipse(Pydev) ???
Thanks !
Click on the play button down arrow in the tool bar -> run configurations -> (double click) Python Run -> Arguments tab on the right hand side.
From there you can fill out the Program Arguments text box:
If you want your program to ask for arguments interactively, then they cease to be commandline arguments, as such. However you could do it something like this (for debugging only!), which will allow you to interactively enter values that the program will see as command line arguments.
import sys
sys.argv = raw_input('Enter command line arguments: ').split()
#Rest of the program here
Note that Andrew's way of doing things is much better. Also, if you are using python 3.*, it should be input instead of raw_input,
Select "Properties" -->> "Run/Debug Settings".
Select the related file in right panel and then click on "Edit" button. It will open properties of selected file. There's an "Arguments" tab.
Years later, and not Eclipse,
but a variant of other answers to run my.py M=11 N=None ... in sh or IPython:
import sys
# parameters --
M = 10
N = 20
...
# to change these params in sh or ipython, run this.py M=11 N=None ...
for arg in sys.argv[1:]:
exec( arg )
...
myfunc( M, N ... )
See One-line-arg-parse-for-flexible-testing-in-python
under gist.github.com/denis-bz .
What I do is:
Open the project in debug perspective.
In the console, whenever the debugger breaks at breakpoint, you can type python command in the "console" and hit return (or enter).
There is no ">>" symbol, so it is hard to discover.
But I wonder why eclipse doesn't have a python shell :(