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

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!

Related

How to remove nonprintable characters in csv file? [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 2 years ago.
Improve this question
I have some invalid characters in my file that I'm trying to remove. But I ran into a strange problem with one of them.
When I try to use the replace function then I'm getting an error SyntaxError: EOL while scanning string literal.
I found that I was dealing with \x1d which is a group separator. I have this code to remove it:
import pandas as pd
df = pd.read_csv('C:/Users/tkp/Desktop/Holdings_Download/dws/example.csv',index_col=False, sep=';', encoding='utf-8')
print(df['col'][0])
df = df['col'][0].encode("utf-8").replace(b"\x1d", b"").decode()
df = pd.DataFrame([x.split(';') for x in df.split('\n')])
print(df[0][0])
Output:
Is there another way to do this? Because it seems to me that I couldn't do it any worse this.
Notice that you are getting a SyntaxError. This means that Python never gets as far as actually running your program, because it can't figure out what the program is!
To be honest, I'm not quite sure why this happens in this case, but using "exotic" characters in string constants is always a bit iffy, because it makes you dependent on what the character encoding of the source code is, and puts you at the mercy of all sorts of buggy editors. Therefore, I would recommend using the '\uXXXX' syntax to explicitly write the Unicode number for the character you wish to replace. (It looks like what you have here is U+2194 DOUBLE ARROW, so '\u2194' should do it.)
Having said that, I would first verify that this is actually the problem, by changing the '↔' bit to something more mundane, like 'x' and seeing whether that causes the same error. If it does, then your problem is somewhere else...
You have to specify the encoding for which this character is defined in the charset.
df = df.replace('#', '', encoding='utf-8')

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.

How to pass unusual arguments to Python script using argparse [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 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.

How come file.readline() works, yet open('name of file', 'r').readline() does not? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have just solved a dilemma that has cost me at least a good 3 hours of my life:
>>> open('foo.py','r')
>>> open('foo.py','r').readline()
>>> ''
I tried various combinations, and to no avail, and of course I asked uncle Google
This as you know howewer, does work
>>> bar=open('foo.py','r')
>>> bar.readline()
>>> 'Crap'
>>> bar.readline()
>>> 'More crap'
>>> bar.readline()
>>> 'Even MORE crap'
>>> bar.readline()
>>> 'End of crap'
So, I always thought that the value assigned to a variable is just that. As simple as this seems
it just can't be, otherwise the code would work either way.
Instead of asking for a direct answer, does anyone have any materials I could go over, probably not
a wiki page, as that's a bit too advanced, but an article of sorts.
In the first instance you aren't calling the function!
open('foo.py','r').readline
If you try it like this:
open('foo.py','r').readline()
You should see behaviour you expected.
Calling readline() on a file object will read from the file until it finds a linebreak and return whatever it has read. During that process, the internal pointer will be positioned on the next line, so another call of readline() will read the next line, until the end of the file is found.
The internal pointer is of course only kept if you keep referring to the same file object. Calling open() will give you such a file object, but calling open() again will just give you another independent file object.
So doing open(…).readline() twice will just open the file, read the first line, and throw away the file object then—twice. The second readline() call will refer to a new file object which of course does not share the pointer from the first one.
So if you want to read through the full file, you should only use one file object and call readline() repeatedly on that one.
Finally note that calling a method actually means adding parentheses at the end. Otherwise, you will just refer to the method without actually calling it.

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)

Categories

Resources