w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python: simple example trying to create a unix command-line executable - why won't it work?
Get rid of the spaces in #! /usr/local/bin/ python so it's #!/usr/local/bin/python. You may also want to make it #!/usr/bin/env python, which will select the first Python interpreter in your path, but that's not recommended for published modules. (Although, neither is /usr/local/bin/python).

Categories : Python

python: import error after making program executable
Your program is trying to run like a bash-script, so it seems, your #!/usr/bin/env python had no effect. Make sure that this line is at the top of the program in the first row with no characters before #

Categories : Python

Errors with Matplotlib when making an executable with Py2exe (Python)
You will need to copy the mpl-data folder too. Check this official wiki site http://www.py2exe.org/index.cgi/MatPlotLib import matplotlib ... setup( ... data_files=matplotlib.get_py2exe_datafiles(), ) You will need something like this in your setup.py for py2exe. hope it helps.

Categories : Python

Making a command line, if statements not working
Calling readLine() on a BufferedReader will only return null on end of input. Here, the input hasn't ended, you've just entered an empty line, so "" (the empty string) is the result. You will need to end the input stream, usually with Ctrl-C. Then you'll get "Why wont you tell me your name!". But then you'll need to break out of your infinite loop.

Categories : Java

Making a GUI operate from the Windows command line
To answer your first question, I recommend creating two different apps, one for command line and one for GUI. The only difference between the two is that one is built with code that handles command line input and the other would have code to use a GUI interface. The two would have in common the rest of the code that is interface agnostic, meaning it will work regardless of the interface. For the second question, there's plenty of tutorials out there for command line parsing, like this one I spent ten seconds to find.

Categories : C++

Making only some Lua scripts on the path runnable from the command line in Windows XP
The trick is that the console PATHEXT mechanism understands "double extensions", i.e. adding a .exe.lua "extension" to PATHEXT will make executable only those Lua scripts which have their full-name ending in .exe.lua (of course you can choose another extension, say .run.lua). Note: I used the quotes to avoid possible confusion and for lack of better terminology (remember that, conventionally, the file extension is the part of the file name after the last dot). Therefore by adding .exe.lua to PATHEXT only whatevername.exe.lua will be executable, whereas any other Lua script won't (provided it doesn't have the same "double extension"). This allows to distinguish "normal" scripts from "executable" ones without either separating them in different directories or define a new custom file exten

Categories : Windows

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

Making the same change to every line in a BED/Interval file in python
step one open the file file = open("somefile.txt") step 2 get the lines lines = list(file.readlines()) file.close() step 3 use a list comprehension new_lines = ["chr"+line for line in lines] step 4 write new lines back to file with open("somefile.txt","w") as f: f.writelines(new_lines) In order to not store all the lines in memory file1 = open("some.txt") file2 = open("output.txt","w") for line in file1: print >> file2, "chr"+ line file1.close() file2.close() then just copy output.txt to your original filename

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

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

Making a .py into a standalone executable with easygui and pygame?
You might want to look at these py2app - http://wiki.python.org/moin/MacPython/py2app py2exe - http://www.py2exe.org/ Both of these can create standalone executable files for your app. They take care packaging all the dependencies into the binary so you don't have to worry about missing libraries.

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

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

Running 7zip command line silently via Python
Pipe stdout and stderr to your system's null file: import os with open(os.devnull, 'w') as null: subprocess.Popen(['7z', 'e', input_file, '-o', output_dest, '-y'], stdout=null, stderr=null)

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

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

Execute process from the windows command line in Python
By trying your code it prints out PreprocessedTufts8199PLAIN.txt.xml file name. I'm not sure if the .txt.xml extension was the desired result. If your file has only .xml extension, then you're not stripping away the original .txt header. Try to change this line: outFile = file(inFile[(str(inFile).rfind('\'))+1:] + '.xml') Into this code: fnameext = inFile[(str(inFile).rfind('\'))+1:] fname,fext = os.path.splitext(fnameext) xmlfname = fname + '.xml' xmlfpath = os.path.join(".", xmlfname) print "xmlfname:", xmlfname, " xmlfpath:", xmlfpath print "current working directory:", os.getcwd() outFile = open(xmlfpath, "r") Answer for extension stripping.

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

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

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

Infinite Amount of Command Line Arguments in Python
You don't need to, command line arguments are stored in sys.argv which will give you a list of the command line arguments. You just need to sum over them. from sys import argv print sum(map(int, argv[1:])) # We take a slice from 1: because the 0th argument is the script name. And just do python testScript.py 1 2 3 6 P.S - Command line arguments are stored as strings, so you need to map them to integers to sum over them. *args is used when you need to pass unknown number of values to a function. Consider the following - >>> def testFunc(*args): return sum(args) >>> testFunc(1, 2, 3, 4, 5, 6) 21

Categories : Python

How can I use python command line arguments that change at run time?
The whole configuration is done at runtime. The examples use string constants for the names, but you are not bound to that. You first load the configuration, then when you have all the elements, simply loop over those and register them as arguments: parser = argparse.ArgumentParser(....) for element in configuration_elements: parser.add_argument('--' + element, type=float, ...) then parse your command line. Alternatively, argparse.ArgumentParser() as a partial parsing mode as well; simply call parser.parse_known_args() to parse everything that argparse does know about, it'll return a namespace object (all the options it could parse) and the remaining arguments it didn't know how to handle: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo')

Categories : Python

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

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

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

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

Is Bash expanding the "*" character in my python command line parameter?
It is because in one of your machine, in the folder, there in no file that could match the pattern. So when this happens, the * remains. You can test with one computer, with and without a file match the pattern. There is another reason, the shell option nullglob is disabled. You can read the GNU bash reference for this.

Categories : Python

Using ProcessBuilder to execute a python script with command line options
Just give them as separate strings in the array, instead of combining the last two into "val_31 val_32": String[] command = {"script.py", "run", "-arg1", "val1", "-arg2", "val2" , "-arg3" , "val_31", "val_32", }; Otherwise it will escape the space in between val_31 and val_32 because you are telling it that they're a single parameter. Incidentally, you can also use the varargs constructor and skip having to create an array, if you want: ProcessBuilder probuilder = new ProcessBuilder( "script.py", "run", "-arg1", "val1", "-arg2", "val2" , "-arg3" , "val_31", "val_32");

Categories : Java

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

How to Run a Command Line python script in IDLE in windows Environment
It doesn't seem like IDLE provides a way to do this through the GUI, but you could do something like: mocking them in your if __name__ == '__main__': where you intercept the command line arguments. try: __file__ except: sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2'] You can also try, idle.py -r scriptname.py arg1 arg2 arg3

Categories : Python

python script runs from command line but using subprocess gives error
When using subprocess.Popen() the first argument should be a list with a separate entry for each argument to the process you want to run: run=subprocess.Popen([sys.executable, 'maps2.py', '-i=/media/babak/LaCie/necessary/visualisation/CMIP3_Babak/Temperature/bccr_bcm2_0', '-o=temp/CMIP3', '-p=temp_001' ]) What you currently have would be the equivalent to running the following on the command line: python 'maps2.py -i=/media/babak/LaCie/necessary/visualisation/CMIP3_Babak/Temperature/bccr_bcm2_0 -o=temp/CMIP3 -p=temp_001'

Categories : Python

python read in multiple key value (dict) from command line into a variable
Use argparse with a custom action: import argparse import copy class DictAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): try: k, v = values.split("=", 1) except ValueError: raise argparse.ArgumentError(self, "Format must be key=value") # Implementation is from argparse._AppendAction items = copy.copy(argparse._ensure_value(namespace, self.dest, {})) # Default mutables, use copy! items[k] = v setattr(namespace, self.dest, items) # Usage: parser = argparse.ArgumentParser() parser.add_argument("--define", action=DictAction) print parser.parse_args("--define k=v --define x=y".split()) # Gives # Namespace(d={'x': 'y', 'k': 'v'}) print parser.parse_args("--define k=v --

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



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