w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

Using windows command line to run python script with passing of url argument
I think the problem is the way you specify your url, it needs to have the http:// part at the start. It works for me when I type python sys.py http://www.google.com/ but fails with python sys.py www.google.com (Note that I am using linux with python 2.7 but I think it may be the same problem for you)

Categories : Windows

How to pass dictionary as command line argument to python script?
Check this: >>> from sys import argv >>> from re import findall >>> args = ' '.join(argv[1:]) >>> pattern = r'([^=]+)s*=s*[s*([^]]+)s*]' >>> d = dict((t[0].strip(), map(lambda x: x.strip(', '),t[1].split())) for t in findall(pattern,args)) >>> for k,v in d.items(): try: d[k] = map(int,v) except: pass >>> d {'names': ['"J.J."', '"April"'], 'years': [25, 29]}

Categories : Python

compare a command line argument with or statment to different strings python
How about using in? if protocol not in ("tcp", "udp"): print" error" sys.exit() FYI, instead of using sys.argv and validating script arguments manually, use argparse module from stdlib. Take a look at choices argument of add_argument method, docs: choices - A container of the allowable values for the argument.

Categories : Python

Python argparse: command-line argument that can be either named or positional
Try to use the "nargs" parameter of the add_argument methode. This way it works for me. Now you can add the username twice, so you have to check it and raise an error, if you want. import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-u", "--user-name", default="admin") parser.add_argument("user_name", default="admin", nargs="?") args = parser.parse_args() print(args)

Categories : Python

Python command line argument semicolon-loop error
If you're writing it in a script, why don't you indent it just the way you would do it in a real python program? Like this: python -mtimeit " n = 0 while n < 10: pass"

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

Passing a command line argument to Python whos string contains a metacharacter
As you said yourself, Python only sees the strings after being processed by the shell. The command-line arguments '-f' and -f look identical to the called program, and there is no way to dsitinguish them. That said, I think that argparse supports a -- argument to denote the end of the options, and everything after this is treated as a positional argument.

Categories : Python

Argument treatment at command line in C
Basically, this is an issue of creating an interface between the operating system and the program. any program. Remember that programs are not always written in C, And you don't even know whether there are things like float or int in the language. You want to be able to pass several arguments (with natural delimiters), which may easily encode arbitrary information. In C, strings can be of arbitrary length, and the only constraint on them is that a zero byte in them signifies the end of the string. this is a highly flexible and natural way to pass arbitrary information to the program. So you can never supply an arbitrary integer/float arguments directly to a program; The operating system (Unix / Linux / Windows / etc.) won't let you. You don't have any tool that gives you that interface,

Categories : C

Passing * as a command line argument
You need to escape the * e.g. by quoting it like "*" or by escaping it like * The expansion of * is done by the shell (before starting your program). Read e.g. the Advanced Bash Scripting guide.

Categories : C

Need help on simple C command line argument
snprintf is the safest way to do this, this is a simple example without any checking of argc etc...: #include <string.h> #include <stdio.h> int main(int argc, char *argv[]) { char buf[200] ; char str1[] = "nmap -sT -p 19 "; char str2[] = " -oG - | grep 19/open > temp"; snprintf(buf, 200, "%s%s%s", str1, argv[1], str2); printf( "%s ", buf ) ;; }

Categories : C

Command line argument to string in C
What you can do is to loop over argv and build a string with strcat char* CommandLine = 0; unsigned int CommandLineLength = 0; unsigned int i = 0; for (i = 0; i < argc; i++) { CommandLineLength += strlen(argv[i]) + 3; // Add one extra space and 2 quotes } CommandLine = (char*) malloc(CommandLineLength + 1); *CommandLine = ''; // Todo: Check if allocation was successfull... for (i = 0; i < argc; i++) { int HasSpace = strchr(argv[i], ' ') != NULL; if (HasSpace) { strcat(CommandLine, """); } strcat(CommandLine, argv[i]); if (HasSpace) { strcat(CommandLine, """); } strcat(CommandLine, " "); } // Do something with CommandLine ... free(CommandLine);

Categories : C

Change a command line argument argv
Did you try debugging? If you do, you will see that it never attempts to erase anything. You can't compare strings (char*) with simple equality, because in reality you're comparing pointers, which will (almost) never be equal. Instead, you should use string comparison functions, like this: if (!strcmp(argv[i], "--item")) { Also, since you're overwriting the argument, you don't need to use a lot of spaces, you can simply set it to an empty string (argv[i] = ""), or modify the existing string to make it empty (argv[i][0] = 0). Alternatively, you could shift the rest of the arguments so you don't end up with gaps which could confuse the rest of your code.

Categories : C++

Nodejs set command line argument as constant
Your init() function is executed after starter.js uses require('./start_server'). When you use require(), the file and all its dependencies are loaded. That means during this process, you also executed require('./common/loghandler'), which completes before server.init() is run in starter.js. Since server.logpath hasn't been set by this time, you get a null value. Aside from that, module.exports is set at require time and changing the values later have no effect. To fix the problems you're having, you should avoid using functions before your application has fully loaded, and put return values in your modules.

Categories : Javascript

perl optional command line argument
The arguments to a subroutine are passed in an array. It looks like you already realise that as you're building up your arguments in @args. If your subroutine is just expecting a list of arguments of arguments, then there are some problems with your approach. Firstly, as you've realised, if you push an empty array onto an array, you will get no items added on to your @args array. And that's going to confuse your subroutine. It's simple enough to test this using Data::Dumper. #!/usr/bin/perl use strict; use warnings; use 5.010; use Data::Dumper; my @arguments = ('Arg1'); my @controller; my @member; my @args; push(@args, $arguments[0]); push(@args, @controller); push(@args, @member); say Dumper @args; The output looks like this: $ ./args $VAR1 = [ 'Arg1' ]; But

Categories : Perl

Parse command line argument using argparse
You can just add options for the arguments you don't need. parser.add_argument("-cdl-sp", dest = "sp", action='store_true') parser.add_argument("-cdl-sk", dest = "sk", action='store_true')

Categories : Python

Command Line Argument as java File
I have this Product file in same package as my main java file. That's not really relevant. Instead, you want Product.java to be in the current working directory when you run the program. (For example, if you run your program as java -jar path/to/program.jar, then you need Product.java to be in the folder that contains path.)

Categories : Java

I wanted to enter a command line argument for my string
Here's a command line arguments tutorial for netbeans. Basically, you go: File->Project Properties->Run->Arguments. In your code, you should probably have: try { if (args.length != 0) { datasetFile = args[0]; in = new BufferedReader(new FileReader(datasetFile)); } } catch(FileNotFoundException e) { e.printStackTrace(); } Your question asks how to enter command line arguments, but it looks like the way you did it worked, since you got a FileNotFoundException on abc, so that's your issue.

Categories : Java

MIPS: Reading a string from command line argument
Here is a few lines of code to illistrate what you are asking: # $a0 = argc, $a1 = argv # 4($a1) is first command line argv 8($a1) is second main: lw $a0, 8($a1) # get second command line argv li $v0, 4 # print code for the argument (string) syscall # tells system to print li $v0, 10 # exit code syscall # terminate cleanly The amount of arguments is in $a0 and you could check the amount of arguments against an integer value loaded (li) into a temporary register for validation purposes. The command line argument values, argv, are stored in $a1 and can be accessed by loading the word. A word is 4 bytes and thus we can access argv[0] with 0($a1), argv[1] with 4($a1) and so forth. In this case we want arg

Categories : Assembly

Export command line argument and set it as constant for a module
the command line arguments are an array of strings called process.argv. This starts with node, then your script, then the additional arguments. To parse the actual options and flags, typically people will use a helper module. Search on npmjs.org to find one you like or implement your own. To store the value, just set it into module.exports.logPath = valueFromCommandLine;

Categories : Javascript

Salt: Can I use an argument from the command line as a jinja variable?
You can do this using Pillar: packages: pkg: - installed - pkgs: {{ salt['pillar.get']('packages') }} Then pass the pillar argument containing valid YAML: salt '*' state.sls package-list pillar='{packages: [foo, bar, baz]}'

Categories : Misc

Boost::Program_options, passing an unknown command line argument
You should remove allow_unregistered() from your parse command. You command should simply be po::store(parse_command_line(argc, argv, desc), vm); then exception will be thrown on unknown options. http://www.boost.org/doc/libs/1_54_0/doc/html/program_options/howto.html#idp123440592 If you want exception/error, if option has no "--" you should write extra parser, something like this, can help you std::pair<std::string, std::string> fix_option(const std::string& value) { std::string name = value; std::string val; std::string::size_type pos = name.find("="); if (pos != std::string::npos) { val = name.substr(pos + 1); name = name.substr(0, pos); } if (name.substr(0, 2) != "--") { throw std::logic_error(std::string("invalid command, no --

Categories : C++

libnet device (Network interface) command line argument
I was confused by the same problem. It can be solve like this. in lib wpcap there is a function named pcap_findalldevs(); use it like this and you will succuss int Value = pcap_findalldevs(&alldevs,errbuf); if( Value == -1) { fprintf(stderr,"Error in pcap_findalldevs: %s ", errbuf); exit(1); } char *device = NULL; device = alldevs->name; //get the first Card name libnet_t *l l = libnet_init( LIBNET_LINK_ADV, device,//use it here error_information); may this help you. good luck!

Categories : Windows

Command line argument as default to a function defined in another module
You can change the default by overwriting the function's func_defaults (__defaults__ in python3.x) attribute: >>> def foo(a=True): ... print a ... >>> foo() True >>> foo.func_defaults (True,) >>> foo.func_defaults = (False,) >>> foo() False >>> I don't know that I would say that this is "pythonic". As far as I'm concerned, the most pythonic solution would be to just pass the argument: import two def main(argv): opts, _ = getopt.getopt(argv, 'hs', ['--strict=']) for opt, _ in opts: if opt in ('-s', '--strict'): config.strict = True two.foo(s=config.strict)

Categories : Python

How to pass Command line argument to specflow test scenario
Specflow doesn't provide any mechanism to do this. While I can see why you might think you want to do this, be careful to consider what is going to happen by linking your tests to an external dependency such as the service that you are going to connect to. While you will have built yourself a means of automating a set of tests, there will be many reasons why they fail. For example, servers not running, configuration not being vaild or even differences in version of client and server. Personally in instances where I have wanted to test the full regression of interprocess communication I have hosted both the client and the server in my tests so that I can more easily control that they start and stop both parts. Even then these tests are very flaky compared with tests that cut out the commu

Categories : C#

How to supply command line argument to perl script through Java
If you don't want to add another command line argument to your script (which is much cleaner and more robust) you need to write to the script's stdin. This snippet should work (Test.java): import java.io.*; public class Test { public static void main(String[] args) { ProcessBuilder pb = new ProcessBuilder("perl", "test.pl"); try { Process p=pb.start(); BufferedReader stdout = new BufferedReader( new InputStreamReader(p.getInputStream()) ); BufferedWriter stdin = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()) ); //write to perl script's stdin stdin.write("testdata"); //assure that that the data is written and does not

Categories : Java

How to escape a variable in bash when passing to command line argument
You need escaped double quoted marks when providing destinationPath in a string. This should work: #!/bin/sh # file paths destinationPath="/cygdrive/c/Documents and Settings/Eric/My Documents/" attachments=" 2013-12-12.pdf" body="Test Body" recipient="asdf@asdf.com" # prepare attachments args="" for file in $attachments ; do file=${file//[ \n]/} touch $file mv $file "$

Categories : Bash

How to pass argument in expect through command line in shell script
If you want to read from arguments, you can achieve this simply by set username [lindex $argv 0]; set password [lindex $argv 1]; And print it send_user "$username $password" That script will print $ ./test.exp user1 pass1 user1 pass1 You can use Debug mode $ ./test.exp -d user1 pass1

Categories : Linux

How to pass special character ('-' for example) as an argument in command line in windows?
I do not think you are right. For PuTTY, a dash (minus) does not have any special meaning, unless it is after a whitespace character. So for your example in the question, PuTTY will use password password-passwordend. While I would not actually expect this, it may be your SSH server that misinterprets dashes in the password.

Categories : Windows

Maximum string length that can be passed in command line argument?
You might modify the C++ and PHP sources and build a pipe. C++ int main () { std::ostringstream txt; txt << std::cin.rdbuf(); std::cout << "Input: " << txt.str() << std::endl; return 0; } PHP <?php $pipe = popen('Debug/Test', 'w'); if( ! $pipe) { // Error } else { $txt = 'Hello World'; fwrite($pipe, $txt, strlen($txt)); pclose($pipe); } ?>

Categories : C++

Passing each line of a file as command line argument to a binary file
Something this simple would normally be best handled by a "scripting" language, but it's pretty straight foreward in C++ as well. If you're reading your file from standard in: std::string args; while ( std::getline( std::cin, args ) ) { system( ("temp " + args).c_str() ); } should be all you need. (But you don't say what you want to do if temp fails.)

Categories : C++

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 retrieve array variable elements passed as a command line argument to Expect script
The expect global variable $argv is a list (i.e. a perl array). If you want to capture it in a different variable: set myvar $argv Or use it directly foreach item $argv { do something with $item }

Categories : Perl

Django `with` tag not recognizing keyword argument
Looks like Django is quite picky about whitespace in this instance. If I change... {% include "entry_table/cell.html" with data_items = data_fields class="entry_table_title" only%} ...to... {% include "entry_table/cell.html" with data_items=data_fields class="entry_table_title" only%} ...it works for me.

Categories : Python

python: better workaround for treating argument in bash/cmd line as an object
You can use the built-in __import__ or the imp module to import object programmatically: # Import 'name' relative to 'path' module = imp.load_module(name, *imp.find_module(name, [path])) Whenever I've wanted to programmatically import modules, this is how I do it, but imp.find_module returns a 3-tuple: fil, path, desc = imp.find_module(name, [path]) module = imp.load_module(name, fil, path, desc)

Categories : Python

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, 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



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