How to pass unusual arguments to Python script using argparse [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have tried using argparse module of Python. I have a special requirement where the argument that I want pass to my Python script will be of below nature :
two arguments with same name, one will start with a '+' sign another with '-' sign. Each will have different significance and separate handling inside the script. For example (+p and -p) as below:
myscript +p music,audio -p application
an argument which will take other arguments starting with '-' as its value and its end will be denoted in a sepcial manner, as below :
myscript -info -name andrew -place newyork -info-
In the above example -info can have values as '-name andrew -place newyork' and the -info- will denote the end of its value.
I tried to achieve it with argparse but was not successful. Only using sys.argv I could manage to pass them. Any help on how can I achieve it with argparse will be great.
Thanks in advance.

two arguments with same name, one will start with a '+' sign another
with '-' sign. Each will have different significance and separate
handling inside the script. For example (+p and -p) as below:
myscript +p music,audio -p application
Just set prefix_chars='-+' when calling argparse.ArgumentParser then you can add separate arguments with ArgumentParser.add_argument() for +p and -p. It's described in the docs here.
While the second one can probably be done, I think it would be a bit complicated and confusing for the user.

Related

what is the output of this python code? I got confused [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm a beginner in programming so I wish you be kind to my question :)
would you please tell me what is the output of this simple code?
It shows error but many say the output is " Learn PY 23 "
how is that possible?!
**def m(name,age=20)
print(name,age)
m("learnPY",23)**
By considering your code as below(removed **)
def m(name,age=20)
print(name,age)
m("learnPY",23)
In function m argument age is given default value, which is applied only if you don't pass 2nd argument while calling function.
In your code you have it with 23 so,
the output will be "LearnPY 23"
If you call m("learnPY") then
the output will be "LearnPY 20"
The code is not syntactically legal Python code.
Hence, the question "what is the output of this Python code" is non-sensical, because it isn't Python code.
Yes, it is. The thing is that the code is wrong formatted.
def m(name,age=20):
print(name,age)
m("learnPY",23)
If you run it correctly, it will work. This is because you're calling the function passing two arguments that will be printed.

read .conf file python ConfigParser [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need to read config.conf file in Python using ConfigParser. The thing I'm trying to do is, club $dataDir variable with a fileName and can't get expected output as given below.
config.conf
[dir]
dataDir = /home/srujan/Documents/r2d2/data-cut/SLIM/postcut
[files]
current_materiel = ${{dataDir}} + /20201209-rtvm_api_current_materiel_not_filtered_OS.csv
Expected output:
/home/srujan/Documents/r2d2/data-cut/SLIM/postcut/20201209-rtvm_api_current_materiel_not_filtered_OS.csv
Debug results - I get as a text instead of dataDir path.
${{dataDir}} + /20201209-rtvm_api_current_materiel_not_filtered_OS.csv
You are looking for https://docs.python.org/3/library/configparser.html#interpolation-of-values.
The default interpolation only allows use of variables from the same section with %(varname) syntax. If you want variables to persist across multiple sections, you need to use the extended interpolation
parser = configparser.ConfigParser(..., interpolation=configparser.ExtendedInterpolation())
Extended interpolation uses ${section:option} to denote a value from a foreign section.

Rename "def" in python (and other keywords) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am trying to write an 'interpretor' for a custom language.
The language is incredibly similar to python, but has some differences eg:
Python:
def subRoutine():
print("hello")
Custom:
sub subRoutine()
print("hello")
What would be the best way to solve this?
Should i modify the python source and recompile, can i write a library that allows me to modify things at such a low level?
Cheers
I would start by this file, keeping in mind that:
Changing the grammar specified in this file will most likely require corresponding changes in the parser module (../Modules/parsermodule.c).
At line 27:
funcdef: 'def' NAME parameters ['->' test] ':' suite
The grammar should however not change for a simple substitution of def, but the whole Python code of the stdlib will be heavily touched by the change.
I have tested it myself, using this source tarball, and replacing the 'def' by 'createfunc' in the Grammar file.
However, during CPython compilation, this error is raised:
Fatal Python error: Py_Initialize: Unable to get the locale encoding
File "/udd/lbourneu/Documents/projects/cpython/Python-3.4.4/Lib/encodings /__init__.py", line 42
def normalize_encoding(encoding):
^
SyntaxError: invalid syntax
You have to replace any def statement by the new one in order to get the python code compiling.
Note: using find . -type f -name "*" -exec sed -i 's/def /createfunc /g' {} + is not enough: 
/usr/bin/mkdir -p Include
python3.4 ./Parser/asdl_c.py -h Include ./Parser/Python.asdl
File "./Parser/asdl_c.py", line 14
createfunc get_c_type(name):
^
SyntaxError: invalid syntax
The command python3.4 ./Parser/asdl_c.py -h Include ./Parser/Python.asdl and this comment show the problem: you need a python to compile python, and both needs to understand the same source code.
The trick introduced by the linked article is to add a keyword instead of replace it.
Later, you can compile a third python that use the second one (which understand both def and sub) for compiling, with a grammar where the def keyword have been totally replaced by the new one.

Literate Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I liked the idea of Literate CoffeeScript and wanted to see if I could get something working with Python. I tried to accomplish something similar to this simple Literate Ruby and ended up with the following. The program takes Literate Python in standard input, a file, or list of files and executes just the code.
import fileinput
import re
code = ''
for line in fileinput.input():
match = re.match(r'([ ]{4}|\t)(.*)', line)
if match:
code += match.group(2) + '\n'
exec code
A simple Literate Python file.
# Python Hello World Program
A simple example of a Literate Python Hello Word program.
print "hello world"
I'm new to Python and wanted to know if I'm missing something or if there is a better solution.
As I said in a comment, eval or exec are evil, a better alternative is to use the code module as in the following example. Also, you may prefer to compile the regex, in order to only perform the matching at each iteration over the input instead of building the automaton at each iteration.
import fileinput
import code
console = code.InteractiveConsole(locals())
import re
r = re.compile(r'([ ]{4}|\t)(.*)')
code = ''
for line in fileinput.input():
match = r.match(line)
if match:
console.push(match.group(2))
Though that example will output the results on sys.stdout so you may want to use instead an overloaded class such as the one in this example.
Combing python and markdown-like syntax is best done using tools rather than changing the language. For example:
sphinx (render output from restructured text in doc strings or other files, both of which may have embedded code samples)
ipython notebook (a combination of "cells" with either markdown or python code)

Trying to call an executable with arguments from Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am using a third party software that I can run in command line which consists of the .exe file as well as several switches that pass through arguments. The goal is to script this using Python but I am a beginner to programming in Python and could use some help in translating the following command line in Python. The arguments are seperated by "/" and the arguments are /inbook1, /inbook2, /report
C:\Program Files(x86)\Florencesoftt\diffenginex\diffenginex.exe /inbook1:"c:\users\file.xlsx /inbook2: "c:\users\file2.xlsx /report:"c:\users\file3.xlsx"
So, would anyone be able to help me call this command using Python?
You want to use the subprocess module.
Exactly how you want to use it depends on exactly what you want to do. For example, do you want to let the program's output mix in with your output, or do you want to capture it to a string? Do you want to wait until it's done, or kick it off in the background?
Fortunately, the documentation is pretty clear, and explains how to do each thing you might want to do.
Meanwhile, I'm 95% sure you've gotten some of the quotes wrong on your command line. For example, the /inbook argument starts with a ", which isn't closed until the start of the /inbook2 argument.
Anyway, trying to guess what you might want, here's one possibility:
args = [r'C:\Program Files(x86)\Florencesoftt\diffenginex\diffenginex.exe',
r'/inbook1:"c:\users\file.xlsx"',
r'/inbook2:"c:\users\file2.xlsx"',
r'/report:"c:\users\file3.xlsx"']
output = subprocess.check_output(args)
The check_output function runs the program, waits for it to finish, raises an exception if it finishes with an error return code, and returns the program's output as a string (or, in Python 3, a bytes).
The extra double quotes probably aren't necessary here (especially since there are no spaces in your pathnames), but since they were in your original code, I left them as-is. Generally, Python will do whatever is necessary to get each separate argument treated as a single argument by the target program, even if you have arguments that have spaces or quotes in them, so you don't have to worry about that.
Mweanwhile, if it's easier to write the arguments as one big string, instead of as a list of four separate strings, you can do that instead. (Only on Windows; don't do it on Unix unless you're using shell=True.) But usually that just means more opportunities to get the quoting wrong, and since you appear to have already gotten it wrong multiple times, I think you're better off this way.
I'm a newbie, but would you like to try this code:
---EDIT---
I've edited so much according to #Abarnert's suggestions that this code is more his than mine, so don't up-vote me. I'm leaving the solution for sake of the fact that now it should work.
The code:
import subprocess
basecommand = r"C:\Program Files(x86)\Florencesoftt\diffenginex\diffenginex.exe"
inbook1 = r"c:\users\file.xlsx"
inbook2 = r"c:\users\file2.xlsx"
report = r"c:\users\file3.xlsx"
inbook1 = r'/inbook1:"' + inbook1 + '"'
inbook2 = r'/inbook2:"' + inbook2 + '"'
report = r'/report:"' + report + '"'
subprocess.call([basecommand, inbook1, inbook2, report])
Thanks #Abarnert!

Categories

Resources