Passing command Line argument to Python script within Eclipse(Pydev) - python

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 :(

Related

How can execute a shell script from spotlight on macOS passing a first command line argument?

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.

How to make a python cmd module command that runs python code

So I'm messing around with the "cmd" module for python, I want a command where you can type "python" and then it opens a python command line. Sort of like how an actual command line would.
Here's my current code.
import cmd
class pythonCmd(cmd.Cmd):
def do_(self, args): # <--- I want this command to have it so you don't type a key word
exec(args)
class cmdLine(cmd.Cmd):
def do_python(self, args):
prompt = pythonCmd()
prompt.prompt = 'python> '
prompt.cmdloop('Python 3.8.2')
prompt = cmdLine()
prompt.prompt = '> '
prompt.cmdloop('Command line starting . . .')
I don't know whether you have to use cmd module or not. But there are much better modules similar to cmd. Modules such as subprocess, os and etc.
I recently used subprocess module, try it.
How about this:
Instead of running your program that opens a shell that can take both python commands and potentially your own commands,
Run python shell, import your program module- you have native python shell that can run python code.
Add support of additional commands by implementing a function like cmd(args) which you can call from the shell. You may need to work on your module to simplify using it in interactive python shell by providing #aliases”to existing functions etc..
With do_shell function you can use it with "!" syntax. For example
> !print("Henlo world")
This would print it, you can use other commands too.

something about “from sys import argv” [duplicate]

I am trying to debug a script which takes command line arguments as an input. Arguments are text files in the same directory. Script gets file names from sys.argv list. My problem is I cannot launch the script with arguments in pycharm.
I have tried to enter arguments into "Script parameters" field in "Run" > "Edit configuration" menu like so:
-s'file1.txt', -s'file2.txt'
But it did not work. How do I launch my script with arguments?
P.S. I am on Ubuntu
In PyCharm the parameters are added in the Script Parameters as you did but, they are enclosed in double quotes "" and without specifying the Interpreter flags like -s. Those flags are specified in the Interpreter options box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0] holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']
For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations (to the left of ) and going to the Edit Configurations. A
gif provided for clarity.
On PyCharm Community or Professional Edition 2019.1+ :
From the menu bar click Run -> Edit Configurations
Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
Click Apply
Click OK
In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:
python mediadb.py /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png
the PyCharm parameter would be:
"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"
Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.
Add the following to the top of your Python file.
import sys
sys.argv = [
__file__,
'arg1',
'arg2'
]
Now, you can simply right click on the Python script.
The first parameter is the name of the script you want to run. From the second parameter onwards it is the the parameters that you want to pass from your command line. Below is a test script:
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
And here is how you pass the input parameters :
'Path to your script','First Parameter','Second Parameter'
Lets say that the Path to your script is /home/my_folder/test.py, the output will be like :
Script is /home/my_folder/test.py
first is First Parameter
second is Second Parameter
It took me some time to figure out that input parameters are comma separated.
I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".
It works in the edu version for me. It was not necessary for me to specify a -s option in the interpreter options.
In edit configuration of PyCharm when you are giving your arguments as string, you should not use '' (these quotations) for giving your input.
Instead of -s'file1.txt', -s'file2.txt'
simply use:
-s file1.txt, -s file2.txt
you can used -argName"argValue" like -d"rd-demo" to add Pycharm arguments
-d"rd-demo" -u"estate"
Arguments added in Parameters Section after selected edit Configuration from IDE
I'm using argparse, and in order to debug my scripts I also using Edit Configuration. For example below the scripts gets 3 parameters (Path, Set1, N) and an optional parameter (flag):
'Path' and 'Set1' from type str.
'N' from type int.
The optional parameter 'flag' from type boolean.
impor argparse
parser = argparse.ArgumentParser(prog='main.py')
parser.add_argument("Path", metavar="path", type=str)
parser.add_argument("Set1", type=str, help="The dataset's name.")
parser.add_argument("N", type=int, help="Number of images.")
parser.add_argument("--flag", action='store_true')
params = parser.parse_args()
In order to to run this in a debug or not by using command line, all needed is:
bar menu Run-->Edit Configuration
Define the Name for your debug/run script.
Set the parameters section. For the above example enter as follow:
The defualt 3 parameters must me included --> "c:\mypath" "name" 50
For the optional parameter --> "c:\mypath" "name" 50 "--flag"
parameter section

Pycharm and sys.argv arguments

I am trying to debug a script which takes command line arguments as an input. Arguments are text files in the same directory. Script gets file names from sys.argv list. My problem is I cannot launch the script with arguments in pycharm.
I have tried to enter arguments into "Script parameters" field in "Run" > "Edit configuration" menu like so:
-s'file1.txt', -s'file2.txt'
But it did not work. How do I launch my script with arguments?
P.S. I am on Ubuntu
In PyCharm the parameters are added in the Script Parameters as you did but, they are enclosed in double quotes "" and without specifying the Interpreter flags like -s. Those flags are specified in the Interpreter options box.
Script Parameters box contents:
"file1.txt" "file2.txt"
Interpeter flags:
-s
Or, visually:
Then, with a simple test file to evaluate:
if __name__ == "__main__":
import sys
print(sys.argv)
We get the parameters we provided (with sys.argv[0] holding the script name of course):
['/Path/to/current/folder/test.py', 'file1.txt', 'file2.txt']
For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations (to the left of ) and going to the Edit Configurations. A
gif provided for clarity.
On PyCharm Community or Professional Edition 2019.1+ :
From the menu bar click Run -> Edit Configurations
Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
Click Apply
Click OK
In addition to Jim's answer (sorry not enough rep points to make a comment), just wanted to point out that the arguments specified in PyCharm do not have special characters escaped, unlike what you would do on the command line. So, whereas on the command line you'd do:
python mediadb.py /media/paul/New\ Volume/Users/paul/Documents/spinmaster/\*.png
the PyCharm parameter would be:
"/media/paul/New Volume/Users/paul/Documents/spinmaster/*.png"
Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.
Add the following to the top of your Python file.
import sys
sys.argv = [
__file__,
'arg1',
'arg2'
]
Now, you can simply right click on the Python script.
The first parameter is the name of the script you want to run. From the second parameter onwards it is the the parameters that you want to pass from your command line. Below is a test script:
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
And here is how you pass the input parameters :
'Path to your script','First Parameter','Second Parameter'
Lets say that the Path to your script is /home/my_folder/test.py, the output will be like :
Script is /home/my_folder/test.py
first is First Parameter
second is Second Parameter
It took me some time to figure out that input parameters are comma separated.
I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".
It works in the edu version for me. It was not necessary for me to specify a -s option in the interpreter options.
In edit configuration of PyCharm when you are giving your arguments as string, you should not use '' (these quotations) for giving your input.
Instead of -s'file1.txt', -s'file2.txt'
simply use:
-s file1.txt, -s file2.txt
you can used -argName"argValue" like -d"rd-demo" to add Pycharm arguments
-d"rd-demo" -u"estate"
Arguments added in Parameters Section after selected edit Configuration from IDE
I'm using argparse, and in order to debug my scripts I also using Edit Configuration. For example below the scripts gets 3 parameters (Path, Set1, N) and an optional parameter (flag):
'Path' and 'Set1' from type str.
'N' from type int.
The optional parameter 'flag' from type boolean.
impor argparse
parser = argparse.ArgumentParser(prog='main.py')
parser.add_argument("Path", metavar="path", type=str)
parser.add_argument("Set1", type=str, help="The dataset's name.")
parser.add_argument("N", type=int, help="Number of images.")
parser.add_argument("--flag", action='store_true')
params = parser.parse_args()
In order to to run this in a debug or not by using command line, all needed is:
bar menu Run-->Edit Configuration
Define the Name for your debug/run script.
Set the parameters section. For the above example enter as follow:
The defualt 3 parameters must me included --> "c:\mypath" "name" 50
For the optional parameter --> "c:\mypath" "name" 50 "--flag"
parameter section

When running a python script in IDLE, is there a way to pass in command line arguments (args)?

I'm testing some python code that parses command line input. Is there a way to pass this input in through IDLE? Currently I'm saving in the IDLE editor and running from a command prompt.
I'm running Windows.
It doesn't seem like IDLE provides a way to do this through the GUI, but you could do something like:
idle.py -r scriptname.py arg1 arg2 arg3
You can also set sys.argv manually, like:
try:
__file__
except:
sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']
(Credit http://wayneandlayne.com/2009/04/14/using-command-line-arguments-in-python-in-idle/)
In a pinch, Seth's #2 worked....
2) You can add a test line in front of your main function call which
supplies an array of arguments (or create a unit test which does the
same thing), or set sys.argv directly.
For example...
sys.argv = ["wordcount.py", "--count", "small.txt"]
Here are a couple of ways that I can think of:
1) You can call your "main" function directly on the IDLE console with arguments if you want.
2) You can add a test line in front of your main function call which supplies an array of arguments (or create a unit test which does the same thing), or set sys.argv directly.
3) You can run python in interactive mode on the console and pass in arguments:
C:\> python.exe -i some.py arg1 arg2
Command-line arguments have been added to IDLE in Python 3.7.4+. To auto-detect (any and older) versions of IDLE, and prompt for command-line argument values, you may paste (something like) this into the beginning of your code:
#! /usr/bin/env python3
import sys
def ok(x=None):
sys.argv.extend(e.get().split())
root.destroy()
if 'idlelib.rpc' in sys.modules:
import tkinter as tk
root = tk.Tk()
tk.Label(root, text="Command-line Arguments:").pack()
e = tk.Entry(root)
e.pack(padx=5)
tk.Button(root, text="OK", command=ok,
default=tk.ACTIVE).pack(pady=5)
root.bind("<Return>", ok)
root.bind("<Escape>", lambda x: root.destroy())
e.focus()
root.wait_window()
You would follow that with your regular code. ie. print(sys.argv)
Note that with IDLE in Python 3.7.4+, when using the Run... Customized command, it is NOT necessary to import sys to access argv.
If used in python 2.6/2.7 then be sure to capitalize: import Tkinter as tk
For this example I've tried to strike a happy balance between features & brevity. Feel free to add or take away features, as needed!
Based on the post by danben, here is my solution that works in IDLE:
try:
sys.argv = ['fibo3_5.py', '30']
fibonacci(int(sys.argv[1]))
except:
print(str('Then try some other way.'))
Auto-detect IDLE and Prompt for Command-line Arguments
#! /usr/bin/env python3
import sys
# Prompt user for (optional) command line arguments, when run from IDLE:
if 'idlelib' in sys.modules: sys.argv.extend(input("Args: ").split())
Change "input" to "raw_input" for Python2.
This code works great for me, I can use "F5" in IDLE and then call again from the interactive prompt:
def mainf(*m_args):
# Overrides argv when testing (interactive or below)
if m_args:
sys.argv = ["testing mainf"] + list(m_args)
...
if __name__ == "__main__":
if False: # not testing?
sys.exit(mainf())
else:
# Test/sample invocations (can test multiple in one run)
mainf("--foo=bar1", "--option2=val2")
mainf("--foo=bar2")
Visual Studio 2015 has an addon for Python. You can supply arguments with that. VS 2015 is now free.
import sys
sys.argv = [sys.argv[0], '-arg1', 'val1', '-arg2', 'val2']
//If you're passing command line for 'help' or 'verbose' you can say as:
sys.argv = [sys.argv[0], '-h']
IDLE now has a GUI way to add arguments to sys.argv! Under the 'Run' menu header select 'Run... Customized' or just Shift+F5...A dialog will appear and that's it!
Answer from veganaiZe produces a KeyError outside IDLE with python 3.6.3. This can be solved by replacing if sys.modules['idlelib']: by if 'idlelib' in sys.modules: as below.
import argparse
# Check if we are using IDLE
if 'idlelib' in sys.modules:
# IDLE is present ==> we are in test mode
print("""====== TEST MODE =======""")
args = parser.parse_args([list of args])
else:
# It's command line, this is production mode.
args = parser.parse_args()
There seems like as many ways to do this as users. Me being a noob, I just tested for arguments (how many). When the idle starts from windows explorer, it has just one argument (... that is len(sys.argv) returns 1) unless you started the IDLE with parameters. IDLE is just a bat file on Windows ... that points to idle.py; on linux, I don't use idle.
What I tend to do is on the startup ...
if len(sys.argv) == 1
sys.argv = [sys.argv[0], arg1, arg2, arg3....] <---- default arguments here
I realize that is using a sledge hammer but if you are just bringing up the IDLE by clicking it in the default install, it will work. Most of what I do is call the python from another language, so the only time it makes any difference is when I'm testing.
It is easy for a noob like me to understand.

Categories