Calling External Command On Python Without Quotes - python

Following the advice given in;
Calling an external command in Python
I have been experimenting using the call() function to call an external command, however the command I need to call is being called correctly but it does not like the parameters being passed to it.
This is because the Call function is passing the parameters with ' 's around them.
E.g
test = call(['/opt/program/something/lookup', 'search "bob"'])
The search part must be passed to the command lookup without any characters surrounding it, I have tried a few different permutations of the call function with varying levels of quotes, spaces, lack of commas etc. The second statement - bob, must be within quotes.
Is there a clean way to do this?
Example of return value of test atm;
Error: 'search "bob"' is not a valid command.

This should work - if not then please update the question with specific error text:
test = call(['/opt/program/something/lookup', 'search', '"bob"'])

Related

How do I stop Python's Sys module's "stdout" and "stderr" write method from returning the numbers of characters written

whenever I use the write method from the stdout or stderr object in Python's built-in "sys" module in Python with the Python interpreter, the method also prints an integer representing the number of characters there are in the string after the string that I provided as an argument for the text parameter for the stdout or stderr method, which is really frustating as I only want the text, not also the string length.
For example:
>>> sys.stdout.write('string')
string6
I only wanted to print "'string'", not the string length (6) as well.
I have tried to solve this problem by using sys.stdout.write('string')[:-1] which I think would also remove the number of characters that is placed after the string
I then found out that the number of characters in the string that I provided as an argument is appearing because I was using the interpreter, and the interpreter prints values that are returned by functions but not printed.
So what I want to do is to call sys.stdout.write('test') but stop it from returning the number of characters in the string that I provided as the text argument. How would I do this?
You cannot stop a ready-made function from doing what it does when you call it. What you can do is stop the Python interpreter from printing the returned value by doing something with it, e. g. assigning it to a variable.
sys.stdout.write also prints the integer after the string that was provided as an argument for the text parameter in the method call because the write method of the stdout object also returns the length of the text parameter's argument, and the Python REPL/Interpreter also prints out returned values, which is the answer for your problem.
So, to stop it from printing out the length of the text string, just assign the sys.stdout.write method call to a variable, as it will call the function and then you can del the variable after it executes, as you will not want the returned number of characters in the string that was provided for the text parameter.
Another solution to this problem is by calling the sdtout object's write method in a function and then calling that function like:
def show_text(txt):
from sys import stdout
stdout.write(txt)
return
show_text('Hello!)

How do I call a function based on user input in Python 3?

I am currently trying to create a program that learns through user input, however it converts to a string automatically.
Here's the code. I use the shelve module to store the commands for the code.
ok = {str(name):func}
asd.update(ok)
print(asd)
data["cmd"] = asd
data.close()
The 'asd' list contains every command which has been extracted from the shelf. I want to update it and store it, so next time it updates when calling a command.
'func' is the variable that stores the name of the function am trying to call, but string objects cannot be called.
How do I solve this?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EDIT:
This has been solved (I totally forgot about eval() )
Not sure what you're trying to achieve here, but from what I've understood you should have a look to eval()
The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
More information here

Python: String formatting when when writing command line instruction

I have a task where I have to run a bunch of simulations with slightly different parameters each time. I'd like to write a Python script to automate this but I'm having an issue.
To simplify the description, I essentially have N simulations called from the command line, each with a different set of parameters, and I'd like the script to execute them one by one. Imagine that to run a simulation I would write execute_simulation... to the command line where the ... stands for the parameters of the given simulation. This is what my script looks like:
from subprocess import call
<code>
for i in range(0, N):
call('execute_simulation_%s' % ( parameters[i]))
However, I always get error messages when calling the script. Can anyone suggest why this might be the case?
It would be helpful if you had included the error messages but I'll try to help you anyway.
The call function expects a sequence of strings not a single string (although the Popen documentation states that they are converted to a string on Windows, so it may working in specific cases).
Also, in the example code you gave, you did call('execute_simulation_%s' % ( parameters[i])). If parameters[i] is not a string but a list, tuple, generator or then str will be called on that object which means you get something like execute_simulation ['arg0', 'arg1', 'arg2', 'arg3', 'arg4']. This is probably not what you want. You can call ' '.join on the sequence to get something like execute_simulation arg0 arg1 arg2 arg3 arg4.
With that being said, I assume that parameters a list of lists containing the arguments for each call. Then you could just do
args = [f'arg{i}' for i in range(5)]
parameters = [args for i in range(5)]
for args in parameters:
call(('execute_simulation', *args))
Also, consider using subprocess.run, since it is recommended to use in Python 3.5+ code (it works just like call).
I hope this works in your case.

Python function parameter as introspectable string

I'm currently building up a library of personal debugging functions, and wanted to make a debugging print function that would provide more quality-of-life functionality than adding print(thing) lines everywhere. My current goal is to have this pseudocode function translated to Python:
def p(*args, **kwargs)
for arg in args:
print(uneval(arg), ": ", arg)
return args
The types of **kwargs and how they'd effect the output isn't as important to this question, hence why I don't use them here.
My main problem comes from trying to have some method of uneval-ing the arguments, such that I can get the string of code that actually produced them. As a use case:
>>> p(3 + 5) + 1
3 + 5: 8 # printed by p
9 # Return value of the entire expression
There's a couple of ways that I see that I can do this, and not only am I not sure if any of them work, I'm also concerned about how Pythonic any solution that actually implements these could possibly be.
Pass the argument as a string, eval it using the previous context's local identifier dictionary (how could I get that without passing it as another argument, which I definitely don't want to do?)
Figure out which line it's being run from in the .py file to extract the uneval'd strings that way (is that even possible?)
Find some metadata magic that has the information I need already in it (if it exists, which is unlikely at best).

Passing a string argument, without quotes, into a function in Python

I have a Python function where the argument is a string of letters and numbers.
The first function call (after function definition) below works, the second returns an invalid syntax error:
def my_function(user):
firstNumber=int(user[0])
secondNumber=int(user[2])
if user[1]!="d":
quit()
else:
return firstNumber+secondNumber
my_function("5d40")
def my_function(user):
firstNumber=int(user[0])
secondNumber=int(user[2])
if user[1]!="d":
quit()
else:
return firstNumber+secondNumber
my_function(5d40)
How can I gracefully handle (eg. simply quit the program) if a user inputs a string into the argument without quotes, so that I don't get an error?
Thanks to everyone for commenting so quickly.
It seems that the answer is, that without quotes around a string argument, it is obviously no longer a string. Furthermore, I will assume that the user will pass correct python syntax when using the function.

Categories