how can i execute python commands(?) in python script? - python

i wonder how to import python console in my python script.
If there are a script named script1.py, that taking string input from console.
What i want to do is that, if i give string input "print(5)" to the script1.py,
than it executes the print(5) (which will give the 5 as result as we use the python console).

Use the python eval() function, as in https://docs.python.org/3/library/functions.html#eval. That evaluates any input string as python code.
For instance:
x = 1
eval('x+1')
2
Be careful with eval though; if the string to be evaluated comes from unprotected user input, it can do anything your own python code can do.

Related

Output of interactive python to shell variable

There is an interactive python script something like
def myfunc():
print("enter value between 1 to 10")
i=int(input())
if(i<1 or i>10):
print("again")
myfunc()
else:
print(i)
I want to store the final output which is print(i) in a shell variable. Something like
python myFile.py | read a
Above query get stuck everytime i run the command. Is it possible to do that?
Even though ( read b | python myFile.py ) | read a defeats the purpose of interactive python function but this doesn't work as well. It works if myfunc() is non-interactive(not expecting user input). The function in reality takes some input, manipulates it, and then output the result in required format. I know it would be much easier to use either python or shell, but since i already wrote the python function, was wondering if it is possible to link both. If yes, is it also possible to add only final value to shell variable rather than all the print()
Same issue happens(terminal gets stuck) when i do
python myFile.py > someFilename
However file someFilename was created even though terminal was unresponsive. It seems shell is starting both the processes at the same time which makes sense. I am guessing if somehow python myfile.py executes independently before opening the pipe it could be possible, but i may be wrong.
If you are working on Linux or other Unix variants, would you please try:
import os
def myfunc():
tty = os.open("/dev/tty", os.O_WRONLY)
os.write(tty, "enter value between 1 to 10\n")
i=int(input())
if(i<1 or i>10):
os.write(tty, "again\n")
myfunc()
else:
print(i)
BTW if your shell is bash, it will be better to say:
read a < <(python myFile.py)
Otherwise read a is invoked in the subshell and the variable a
cannot be referred in the following codes.

Some functions from library works in python shell but not in a script

I'm having trouble getting certain functions from a library called art (https://github.com/sepandhaghighi/art) to run in a script, though they work fine in a shell. The script/commands entered sequentially look like this:
from art import *
randart() <(function fails in script, but succeeds in shell)
tart("test") <(different function, same library, succeeds in both shell and script)
import sys
print(sys.version)
The python version is 3.7.5 for both the shell and the script. The first function does not throw an error when run in a script, but does not give any output. Its desired output is a random ascii_art from a collection. I feel like I'm missing something really simple. Any ideas? The documentation on github reports "Some environments don't support all 1-Line arts", however they are the same python version on the same machine. Are there other portions of the environment that could be the cause?
You need to print randart() while writing in script. Make a habit of using print() for everything while printing. Shell is the place which returns the value by default whereas you need to tell the script window what to do with any name or function.
so use this:
from art import *
print(randart())
in the shell it is implicitly printed ... in a script you must explicitly
print(randart())

Intrepret bytecode with subprocess.call argument

I have a program that take one argument.
I need to call this program in my python script and I need to pass the argument in bytecode format (like \x42\x43).
Directly in bash, I can do like this and it does work:
./myprogram $'\x42\x43'
But with subprocess.call it doesn't work:
subprocess.call(["myprogram", "$'\x42\x43'"])
Bytes are not intrepreted.
I try to call my program with /bin/bash but my program returns a segfault!
A quick thing to note: $ is a bash construct. It is the one which evaluates the variable and returns it's value. This does not happen in general when calling one program from another program. So when you invoke myprogram it is up to you to provide all the arguments in a form in which myprogram understands them.
Thanks #acw1668
This works well:
subprocess.call(["myprogram", b"\x42\x43"])
But if yours bytecodes are in a variable, you need to do this manipulation:
# If you're string is unicode type
mystring = mystring.decode('unicode_escape')
# I choose latin1, because some of my bytecode are bigger than 128
mystring = mystring.encode('latin1')
And my bytecodes are correctly interpreted:
subprocess.call(["myprogram", mystring])

How to use python to start an interactive shell program?

I have used python subprocess and os module for a while. Now I want to start an interactive C++ program called dumbCalculator from python. This dumbCalculator simply read my input and return its result: when I type 1+2 it returns 3
How can I use my python script to call this dumbCalculator binary? apparently, when dumbCalculator starts, python need to 'give up' its shell.
Any comments?
Thanks a lot!
Either of these two commands will run an interactive program for you and return to Python when the program ends. They will not necessarily return a value from that program. 'bc' is an interactive calculator for testing. It will let you add numbers and then return to Python when you type 'quit'.
>>> os.system("bc")
>>> subprocess.call("bc")

Fail to pass multiple arguments to a python script in command line

I was trying to write a python script like this:
import sys
print sys.argv[1]
print sys.argv[2]
Let's call it arg.py, and run it in command line:
python arg.py one two
it printed: one two.
Everything was fine.
Then I wanted it to be handy so I put arg.py in my $PATH and gave it permission to exacuate so wherever I'm I can simply type arg in command line to run this script. I tried
arg one two
but it failed. The exception said:"bash: test: one: unary operator expected". But if I just do
arg one
it worked fine.
My question is: why I can't pass multiple arguments like this? And what is the right way?
Thanks!
You probably named your script test, which is a Bash builtin name. Name it something else.
$ help test
test: test [expr]
Evaluate conditional expression.
Exits with a status of 0 (true) or 1 (false) depending on
the evaluation of EXPR. Expressions may be unary or binary. Unary
expressions are often used to examine the status of a file. There
are string operators and numeric comparison operators as well.
The behavior of test depends on the number of arguments. Read the
bash manual page for the complete specification.
...
That's why you're getting the error from bash:
bash: test: one: unary operator expected
^--------- because it expects an operator to go before 'two'
^-------- and test doesn't like the argument 'one' you've provided
^-------- because it's interpreting your command as the builtin 'test'
^--- Bash is giving you an error
You should parse command line arguments in Python using argparse or the older optparse.
Your script, as it is, should work. Remember to put a shebang line that tells bash to use Python as interpreter, e.g. #! /usr/bin/env python

Categories

Resources