python problam subprocess fore rub script bash - python

i have problem in subprocess
i have this script bash which good work and is name kamel.sh
to=$1
subject=$1
/root/Desktop/telegram/tg/bin/./telegram-cli -k /root/Desktop/telegram/tg/tg-server.pub -WR -e "msg $to $subject"
but i want use python fore work.is 1.sh give 2 argv fore work and argv1 = user and argv2 = hello
but is have problem
import subprocess
subprocess.call("1.sh", user, hello, shell=True )
and i see this eroore
Traceback (most recent call last):
File "/root/Desktop/telegram-log/kamel.py", line 27, in <module>
subprocess.call("kamel.sh testt",kol,shell=True )
File "/usr/lib/python2.7/subprocess.py", line 523, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 660, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

import subprocess
subprocess.call("1.sh user hello", shell=True)
or
import subprocess
subprocess.call(["1.sh", "user", "hello"])

Related

'str' object has no attribute 'fileno'

I want to open git bash and write git commands into it.
I used following code:
from subprocess import Popen, PIPE
process = subprocess.run(['D:\\casdev\\SmartGit\\git\\git-bash.exe'],shell= "True", bufsize=0,stdin="git status",stdout=PIPE, stderr=PIPE, encoding="UTF8")
stdoutput, stderroutput = process.communicate()
response=process.stdout.read()
Output:
runfile('C:/Users/uib25171/Desktop/MiniProject/Trials/untitled3.py', wdir='C:/Users/uib25171/Desktop/MiniProject/Trials')
Traceback (most recent call last):
File "<ipython-input-66-00c2c0a9827c>", line 1, in <module>
runfile('C:/Users/uib25171/Desktop/MiniProject/Trials/untitled3.py', wdir='C:/Users/uib25171/Desktop/MiniProject/Trials')
File "C:\Users\uib25171\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\uib25171\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/uib25171/Desktop/MiniProject/Trials/untitled3.py", line 37, in <module>
process = subprocess.run(['D:\\casdev\\SmartGit\\git\\git-bash.exe'],shell= "True", bufsize=0,stdin="git status",stdout=PIPE, stderr=PIPE, encoding="UTF8")
File "C:\Users\uib25171\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\uib25171\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 143, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
File "C:\Users\uib25171\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 728, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "C:\Users\uib25171\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 1039, in _get_handles
p2cread = msvcrt.get_osfhandle(stdin.fileno())
**AttributeError: 'str' object has no attribute 'fileno'**
Can somebody help me?
It seems as if your passing a string instead of an input stream at stdin="git status"
You are mixing stdin, which should be a filehandle, with input, which lets you pass a string as input to your subprocess. But more fundamentally, you are mixing apples and oranges. communicate makes sense for a bare Popen object, but that's not what subprocess.run returns. The output from your command is simpy process.stdout.
But really you should probably be running
process = subprocess.run(['git', 'status'],
text=True, encoding="UTF8", capture=True)
response = process.stdout
If you need shell=True (which you don't here) you can pass the path to Bash in the executable= keyword parameter.
You messed up your code. #tripleee already explained. this is probably what you want -
from subprocess import PIPE
import subprocess
process = subprocess.run(['your_file_name'],shell= "True", bufsize=0,stdin=PIPE,stdout=PIPE, stderr=PIPE, encoding="UTF8")
response=process.stdout

Python3.5 subprocess error

I am using below function to read my python scripts output line by line and save in parallel. But getting Traceback error in end.
Code:
def myrun(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = []
while True:
line = p.stdout.readline()
stdout.append(line)
print (line),
if line == '' and p.poll() != None:
break
return ''.join(stdout)
When call function as :
myrun(os.system("./tests_run.py"))
I get below error:
Error:
Traceback (most recent call last):
File "./Portability_Tests.py", line 38, in <module>
myrun(os.system("./tests_run.py"))
File "./Tests.py", line 11, in myrun
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
File "/usr/local/lib/python3.5/subprocess.py", line 676, in __init__
restore_signals, start_new_session)
File "/usr/local/lib/python3.5/subprocess.py", line 1171, in _execute_child
args = list(args)
TypeError: 'int' object is not iterable
Anyone know how can i fix this error ?
The subprocess.Popen function receives a "sequence of program arguments or else a single string" as its args argument.
What you are passing in the args argument is the output of the os.system() call which according to the documentation is the "exit status of the process", thus an int number. Instead in the cmd variable you should directly pass the string (or an other iterator) of your file /tests_run.py. If you want this path to be relative to your current project you can use the os.path module.

Execute Robot Framework file from python script

from subprocess import call
import os
call(['robot '+os.getcwd()+'\\aaa.robot'])
file_dir: D:/aaa/test/aaa.robot
script for now in same dir
Output:
Traceback (most recent call last):
File "__init.py", line 7, in <module>
call(['robot '+os.getcwd()+'\\aaa.robot'])
File "C:\Python27\lib\subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 710, in __init_
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execut
startupinfo)
WindowsError: [Error 2] Nie mo┐na odnalečŠ okreťlonego pliku
I just cant handle it. I dont get why in python tunning anything is so complicated :(
I want same result as this line (written directly to cmd):
/>robot aaa.robot
Here is another way
import robot
logFile = open('mylog.txt', 'w')
robot.run("tmp.robot",stdout=logFile)
subprocess expects a list but you're inputting a string ('robot '+os.getcwd()+'\\aaa.robot').
Try:
call(['C:/Python27/python.exe', '-m', 'robot', 'D:/aaa/test/aaa.robot'])
or
call(['C:/Python27/Scripts/robot.bat', 'D:/aaa/test/aaa.robot'])

Error using subprocess.check_output in Python

I am at a very basic level in Python, and I'm trying to learn how to use the subprocess module. I have a simple calculator program called x.py that takes in a number, multiplies it by 2, and returns the result. I am trying to execute that simple program from IDLE with the following two lines of code, but I get errors. The number 5 is the number I'm trying to feed into x.py to get a result. Would someone mind helping me understand what I'm doing wrong and help me get it right? Thanks!
import subprocess
result = subprocess.check_output(["C:\\Users\\Kyle\\Desktop\\x.py",5])
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
result = subprocess.check_output(["C:\\Users\\Kyle\\Desktop\\x.py",5])
File "C:\Python27\lib\subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 855, in _execute_child
args = list2cmdline(args)
File "C:\Python27\lib\subprocess.py", line 587, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: argument of type 'int' is not iterable
Pass 5 as a string:
import sys
result = subprocess.check_output([sys.executable, "C:\\Users\\Kyle\\Desktop\\x.py", '5'])

Python subprocess command arguments

Why if I run subprocess.check_output('ls') everything is working but when I add argument to command like: subprocess.check_output('ls -la') I get error:
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
How can I pass command arguments into subprocess.check_output()?
You need to split the arguments into a list:
subprocess.check_output(['ls', '-la'])
The subprocess callables do not parse the command out to individual arguments like the shell does. You either need to do this yourself or you need to tell subprocess to use the shell explicitly:
subprocess.check_output('ls -la', shell=True)
The latter is not recommended as it can expose your application to security vulnerabilities. You can use shlex.split() to parse a shell-like command line if needed:
>>> import shlex
>>> shlex.split('ls -la')
['ls', '-la']
You might find sh.py more friendly:
import sh
print sh.ls("-la")

Categories

Resources