w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
How to run python program on command line with different input possibilities
You'll have to make all arguments optional and validate them yourself: ap=argparse.ArgumentParser() ap.add_argument('-c', required=False) ap.add_argument('a', nargs='?') ap.add_argument('b', nargs='?') args = ap.parse_args() if (args.c is not None): # process c elif (args.a is not None and args.b is not None): # process a and b else: # validation errors If you were willing to make a and b a single named parameter instead of positionals, you could use mutual exclusion to do this for you. Mutually exclusive groups require all parameters in them to be optional, and named parameters can only be required. ap=argparse.ArgumentParser() g = ap.add_mutually_exclusive_group(required=True) g.add_argument('-ab', nargs=2, required=False) g.add_argument('-c', required=False) args =

Categories : Python

OpenCV using command line argument for input image (Python)
In python and most other languages argv[0] contains the program name. Try using argv[1] to get the correct result. Here is some Python Documentation to help you. Python has an amazing library of documentation I highly recommend using it.

Categories : Python

Command Line Python Comma Separated User Input int Values
"2,3" is a string, passing this to a function won't make it act like two different parameters separated by ,(as you expected). >>> def func(arg): ... print arg ... >>> func('a, b') a, b # arg is a variable that stores the passed string You should convert that string into two numbers first by splitting it at comma first and then applying int() to each if it's item. >>> import math >>> math.pow(*map(int, '2,3'.split(','))) 8.0 First split the string at ',' using str.split: >>> '2,3'.split(',') ['2', '3'] #str.split returns a list Now as we need integers so apply int() to each value: >>> map(int, '2,3'.split(',')) #apply int() to each item of the list ['2', '3'] [2, 3] Now as pow expects tw

Categories : Python

How do I accept user input on command line for python script instead of prompt
Replace src = input('Enter Path to src: ') with: import sys src = sys.argv[1] Ref: http://docs.python.org/2/library/sys.html If your needs are more complex than you admit, you could use an argument-parsing library like optparse (deprecated since 2.7), argparse (new in 2.7 and 3.2) or getopt. Ref: Command Line Arguments In Python Here is an example of using argparse with required source and destination parameters: #! /usr/bin/python import argparse import shutil parser = argparse.ArgumentParser(description="Copy a file") parser.add_argument('src', metavar="SOURCE", help="Source filename") parser.add_argument('dst', metavar="DESTINATION", help="Destination filename") args = parser.parse_args() shutil.copyfile(args.src, args.dst) Run this program with -h to see the help message.

Categories : Python

Flyway command line filesystem migrations from actual command line input
flyway.cmd -configFile=/path/to/other/configFile.conf should do what you want. I just checked and it seems I forgot to document this on the website (It is in the usage description of the tool itself). Could you file an issue against the website, requesting this to be added?

Categories : Windows

Reading input files by line using read command in shell scripting skips last line
DONE=false until $DONE do read line || DONE=true echo $line done < blah.txt How to use `while read` (Bash) to read the last line in a file if there’s no newline at the end of the file?

Categories : Bash

Is possible to list the git repository issues in command line?
No, not directly with the "vanilla" git command line. There is a "command-line wrapper for git that makes you better at GitHub." (according to the site) http://hub.github.com/ You can then run: $ git browse -- issues Which would return the current projects issues. EDIT In that case, this may be more helpful. It's a cli to github

Categories : GIT

Always given command line before python fabric command is executed on remote
Interesting, I don't have such issue, your code works fine for me (up to adding env.key_filename and env.password) c:work>fab hello [x.x.x.x] Executing task 'hello' [x.x.x.x] run: touch hello.world Done. Disconnecting from x.x.x.x... done. I'm using Fabric 1.7.0 and Paramiko 1.11.0. Possibly it's a problem of the terminal on your server.

Categories : Python

Defining the command line arguments of a linux command in python
format is your friend: import os, sys if len(sys.argv) == 2: os.system("sudo rtcwake -m off -s {}".format(sys.argv[1])) else: print "usage: ..." so the seconds are command line parameters. Or, you can make it interactive: import os secs = raw_input() os.system("sudo rtcwake off -s {}".format(secs)) to verify that the user input is an integer: try: secs = int(secs) except: print 'usage: '

Categories : Python

How to read the input(line by line) from a multiline Tkinter Textbox in Python?
From the document, the get method on tkinter.text will just return the string, including the new line . You can not treat the tkinter.text as file, but you can use other ways. Read them all and split them into a list. Loop the list then. def retrieve_input(): text = self.txt.get('1.0', END).splitlines() for line in text: ... Using io.StringIO to emulate a file, but in this case it will not strip the newline. def retrieve_input(): text = io.StringIO(self.txt.get('1.0', END)) for line in text: line = line.rstrip() ...

Categories : Python

How to pipe input to python line by line from linux program?
I do not quite understand why you want to use commandline arguments instead of simply reading from standard input. Python has a simple idiom for iterating over lines at stdin: import sys for line in sys.stdin: sys.stdout.write(line) My usage example: $ echo -e "first line second line" | python python_iterate_stdin.py first line second line Your usage example: $ echo "days go by and still" | python python_iterate_stdin.py days go by and still

Categories : Python

java processing input from command line
By using the st.pop() it will remove and return the last item of the stack. If you dont want it to get removed you can use one ordered Collection like ArrayList and access the item by list.get or using an Iterator. Another suggestion is to create one object to store the name and the y, x properties: class MyObject { private String name; private int x; private int y; //... setter and getter methods for the properties } Suggestion for your code: it pushes the input in the Stack, then pop the items to create the MyObject and add to the list: ArrayList listObjects = new ArrayList(); Scanner input = new Scanner(System.in); Stack st = new Stack(); while(input.hasNext()){ String tkn = input.next(); st.push(tkn); if (st.size()==3){ int

Categories : Java

multiple input parameters from command line in C
To be able to call a function that you have as a string, you have know which name is paired to which function. If all functions take the same arguments, you can have an array of structures with name and function pointer, and then match the name with the correct entry in the table. Otherwise, if the arguments are different you have to have a chain of strcmp calls to call the correct function.

Categories : C

Read file as input from the command line
When a program is invoked like this ./a.out < file, the content of the file will be available on the standard input: stdin. That means that you can read this content by reading the standard input. For example: read(0, buffer, LEN) would read the from your file. getchar() would return a char from your file.

Categories : C++

Take in escaped input in Ruby command line app
p eval(""#{gets.chomp}"") Example use:  # Input by the user from the keyboard " " # Value from the script %A %d %i, %u # Input by the user from the keyboard "%A %d %i, %u" # Value from the script

Categories : Ruby

Check command line arguments for input value
A switch statement isn't really called for here. That's useful when you have a single value and need to select from a series of possible mutually-exclusive steps based on that value. But that's not what you're doing here. These aren't a chain of if/else if statements keying off a value, these are more like guard clauses. All of them need to run in order to determine all of the output to show to the user. You can shorten the code by removing the curly braces: if (!(programName.Equals("Army"))) Console.WriteLine("Error"); if (!Int32.TryParse(args[1].ToString(), out isNum )) Console.WriteLine("value should be a number"); if (!File.Exists(file1)) Console.WriteLine("file 1 does not exist"); if (!File.Exists(file2)) Console.WriteLine("file 2 does not exist"); You could a

Categories : C#

How to get piped input to ruby -e on command line?
Ruby treats your line as a comment because it starts with a #. This would work: echo "My String" | ruby -e "puts gets.downcase" Output: my string I've used Kernel#gets instead of STDIN.gets: Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line If you want to process each line, you could use the -p flag. It's like wrapping your script in a while gets(); ... end; puts $_ block. Ruby reads each input line into $_, evaluates your script and outputs $_ afterwards: echo "Foo Bar Baz" | ruby -pe '$_.downcase!' Output: foo bar baz

Categories : Ruby

How to provide file input from command line arguments in R
Have a look at ?commandArgs. Minimal example: #!/usr/bin/Rscript print(commandArgs(trailingOnly=TRUE)) Run it: ./myscript.R yourcsvfile.csv [1] "yourcsvfile.csv" Maybe you will be interested in the getopt package, too.

Categories : R

Automatically fill command line input of variable size
yes $'a b' | script.py Uses bash's $'...' syntax for string literals which contain escape sequences. Alternatively: while true; do echo a; echo b; done | script.py

Categories : Python

C++ command line utility input file location changes behaviour
For your first error with drawingtotext P1-1522-YI-WD-0403r1.dxf command, are you sure the executable was in the same folder as P1-1522-YI-WD-0403r1.dxf? The second error occurs when you free memory that has not been allocated. From looking at your code, this error must be occurring on the delete input or delete output lines near the end, seeing as that's the only place you're freeing any memory. You said "running this gives me what I expect plus this [error] at the end?" If the output is created just like you want, and the only thing wrong is this error, then you can account for it by adding: if (input != null) delete input; if (output != null) delete output; to avoid freeing memory that is not allocated. But again this only fixes your problem if the output is correct like you

Categories : C++

Formatting input from excel to mysql using command line client
seems u have used '|' in your csv file as delimiters instead of comma, try the code as `LOAD DATA LOCAL INFILE 'path to file.csv' INTO TABLE table_name FIELDS TERMINATED BY '|'LINES TERMINATED BY ' ';`

Categories : Mysql

How to switch between python 2.7 to python 3 from command line?
For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3. To add Python 3 to the environment variables, follow these steps - Right Click on My Computer and go to Properties. Go to Advanced System Settings. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory. For example,

Categories : Python

Getting Command line in Python
Just use sys.argv, like this: import sys # this part executes when the script is run from the command line if __name__ == '__main__': if len(sys.argv) != 2: # check for the correct number of arguments print 'usage: python kb.py cur' else: call_your_code(sys.argv[1]) # first command line argument Note: sys.argv[0] is the script's name, and sys.argv[1] is the first command line argument. And so on, if there were more arguments.

Categories : Python

Run sqlite3 with python in command line
Python itself dosen't contain a sqlite3 command. But the SQLite library includes a simple command-line utility named sqlite3 (or sqlite3.exe on windows) that allows the user to manually enter and execute SQL commands against an SQLite database. You can download it from here.

Categories : Python

Python - Need to get argument on command line
argparse is beautiful. Redesign your command line interface for it or write your own CLI-parser. CLI example: args = ['firstargument', 'secondargument', '-s', 'thirdargument', '-s', 'fourth', 'fifth', '-s', 'sixth'] last_arg = None container = [] marker = '-s' for arg in args: if (arg != marker): last_arg = arg else: container.append(last_arg) print container Result of execute: $python test.py ['secondargument', 'thirdargument', 'fifth']

Categories : Python

Python, Command Line, Windows
After modifying your path, did you start up a new instance of the command prompt (this has caused me much grief in the past)? To check if your path change was successful: echo %PATH% and check to see if C:Python2.7.5 was appended to it. If not then run: set PATH=%PATH%;C:Python2.7.5 To call a python script with a command line argument (assuming that your script is in the current working directory): python letter_counts.py "Your Text Goes Here" OR if you just want to be overly verbose (or your PATH still isn't right): C:Python2.7.5python.exe .letter_counts.py "Your text still goes here" EDIT: Make sure you are doing this from the command prompt and not the python interpreter. To access the command prompt you can hit: 1. Windows Key + R 2. type "cmd" (without quotes) and hit

Categories : Python

Turn python input into command
Assuming you are using Python 3, on Python 2 you would use raw_input instead while 1: c = input() exec(c) note that you can't trust that people won't enter malicious code here You may also want to wrap this in a try/except to print the traceback when an Exception occurs and continue the loop: import traceback while 1: try: c = input() exec(c) except: print(traceback.format_exc())

Categories : Python

Basics of Command Line Arguments, Python
You want to use the sys.argv list from the sys module. It lets you access arguments passed in the command line. For example, if your command line input was python myfile.py a b c, sys.argv[0] is myfile.py, sys.argv[1] is a, sys.argv[2] is b, and sys.argv[3] is c. A running example (testcode.py): if __name__ == "__main__": import sys print sys.argv Then, running (in the command line): D:some_path>python testcode.py a b c ['testcode.py', 'a', 'b', 'c']

Categories : Python

Complete as-you-type on command line with python
I would try with "curses" library: http://docs.python.org/2/library/curses.html You have a related topic at: How to make python autocompletion display matches?

Categories : Python

How To Run A Python File From Windows Command Line
If you want to know How do I run a .py file from the Python interpreter? this will work import sys sys.path.append("C:\Users\Myname\Desktop\Python") import Python-Test But your question says from the command line, which has been answered in the comments.

Categories : Python

how to input a respond to prompt of a command by python?
If you're running on some UNIX variant, you can do yes N | <program> which feeds a never-ending stream of "N"s to the program. If you want to control a console-driven program from Python, consider using pexpect. This library enables very simple interaction: import pexpect pexpect.spawn("<cmd>") while 1: child.expect(r'[y/N]') child.sendline('N')

Categories : Python

Command line arguments as variable definition in Python
This is a relatively simple task with ast.literal_eval and string splitting -- But only if you have a really well defined syntax. (e.g. only 1 of --foo=bar or --foo bar is allowed). import argparse import ast parser = argparse.ArgumentParser() #allow the creation of known arguments ... namespace,unparsed = parser.parse_known_args() def parse_arg(arg): k,v = arg.split('=',1) try: v = ast.literal_eval(v) #evaluate the string as if it was a python literal except ValueError: #if we fail, then we keep it as a string pass return k.lstrip('-'),v d = dict(parse_arg(arg) for arg in unparsed) print(d) I've put the key-value pairs in a dictionary. If you really want them as global variables, you could do globals().update(d) -- But I would seriously a

Categories : Python

Hadoop mapreduce python command line arguments
You can read the input file from os.environ. For example, import os input_file = os.environ['map_input_file'] Actually, you can also read other JobConf from os.environ. Note: During the execution of a streaming job, the names of the "mapred" parameters are transformed. The dots ( . ) become underscores ( _ ). For example, mapred.job.id becomes mapred_job_id and mapred.jar becomes mapred_jar. To get the values in a streaming job's mapper/reducer use the parameter names with the underscores. See Configured Parameters. I also find a very useful post for you: A Guide to Python Frameworks for Hadoop.

Categories : Python

Python arguments cuts at < when reading from command line
you need to escape the < sign. try calling: python time.py python ratatosk.py < input.txt it might be better to use a different character than < so that running this command is easier

Categories : Python

How do I run Python script using arguments in windows command line
To execute your program from the command line, you have to call the python interpreter, like this : C:Python27>python hello.py 1 1 If you code resides in another directory, you will have to set the python binary path in your PATH environment variable, to be able to run it, too. You can find detailed instructions here.

Categories : Python

How to open a window from the command line within a Python script?
You can use subprocess module. subprocess is a newer way to spawn processes rather than using os.spawn*() or os.system(). In your case: import subprocess subprocess.Popen(["ds9"]) This should run ds9 in background. See the documentation here.

Categories : Python

Why does python's recursive copy not work the same as on the command line?
Seems os.system changes the shell it executes in to sh: mike@mike-VirtualBox:~/head$ echo $0 bash mike@mike-VirtualBox:~/head$ python Python 2.7.3 (default, Apr 10 2013, 06:20:15) >>> import os >>> os.system("echo $0") sh When the copy command is executed via Popen with a bash shell, it works as expected: >>> import subprocess >>> sp.Popen("cp -rf ./applications/icom_app_template ./applications/my_dir", shell=True, executable="/bin/bash") >>> exit() mike@mike-VirtualBox:~/head$ tree ./applications/my_dir/ ./applications/my_dir/ ├── cdl │ ├── include │ ├── Makefile │ ... │ └── other ├── cds │ ├── include ... The only oddity that I do not have an answer for is that if I

Categories : Python

Python: Multi-threaded Command Line Animation
I think curses would do the job. Have a look at what is possible in this example

Categories : Python

How can I read the Command Line feedback from Python os.system()?
With your eyes. os.system only returns a number back to your process. You should use the subprocess module to read the stdout back into your process eg subprocess.check_output result = subprocess.check_output(['snmpget', '-v', '3', '-u', 'initial', '172.17.171.113', '1.3.6.1.2.1.1.5.0'])

Categories : Python

Run a pydev module from python or ipython or command line?
two options: 1) set $PYTHONPATH in your ~/.bash_profile. This will affect both python and ipython. 2) make ipython change the path on startup. edit your ipython startup script, very likely something like ~/.ipython/profile_default/startup/00run.ipy, and add import sys path = 'path/to/project' if not path in sys.path: sys.path.insert(1, path) del path if you are working in ipython a lot in that project, you may add %cd 'path/to/project' to the startup file as well.

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.