Error using subprocess.check_output in Python - 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'])

Related

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'])

run a .exe file with additional parameters

I am using windows and struggeling to get this work...
I can execute this in cmd.exe:
"C:\Program Files (x86)\Test 123\Test.exe" "H:\Test Test\file.txt" -f "doStuff"
but when I try to do it in python:
subprocess.call([r'"C:\Program Files (x86)\Test 123\Test.exe" "H:\Test Test\file.txt" -f "doStuff"'])
I get this error:
Traceback (most recent call last):
File "testing12.py", line 20, in <module>
subprocess.call([r'"C:\Program Files (x86)\Test 123\Test\Test.exe" "H:\Test Test\Folder\file.txt" -f "doStuff"'])
File "c:\Python27\lib\subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "c:\Python27\lib\subprocess.py", line 709, in __init__
errread, errwrite)
File "c:\Python27\lib\subprocess.py", line 957, in _execute_child
startupinfo)
WindowsError: [Error 5] Access is denied
How can I execute it properly? Thanks.
If you're going to pass in an array, make it an actual array -- one argument per parameter, separated by commas. Otherwise you'll need to use shell=True, which has all the (generally undesirable) side effects of invoking a shell (and should just pass in your command string as a string, no array called for in that use case).
subprocess.call([
"C:\Program Files (x86)\Test 123\Test.exe",
"H:\Test Test\file.txt",
"-f", "doStuff"])
If you don't use commas between your strings, they're consolidated together.

Python: Passing arguments when running an external command

I am calling an external program like this
call(["./myProgram", myArgs])
How can I pass a list of arguments? myProgram takes 3 parameters like this
myProgram param1 param2 param3
specifiying arguments seperately like below works
call(["./myProgram", param1 ,param2, param3])
, but how can I use a list/array of arguments, like
myArgs=[param1,param2,param3]
I am getting this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception TypeError: execv() arg 2 must contain only strings
Just concatenate the lists:
call(['./myProgram'] + myArgs)
The first argument must be a list of strings; simply build that list from two separate lists.

NamedTemporaryFile cannot be acessed from command line

I have the following (simplified) code:
with NamedTemporaryFile() as f:
f.write(zip_data)
f.flush()
subprocess.call("/usr/bin/7z x %s" % f.name)
It dies with the following error:
Traceback (most recent call last):
File "decrypt_resource.py", line 70, in <module>
unpack(sys.argv[2])
File "decrypt_resource.py", line 28, in unpack
print(subprocess.check_output(cmd))
File "/usr/lib/python2.7/subprocess.py", line 568, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
However, if I use NamedTemporaryFile(delete=False) and then print & execute the command, it works. What's wrong here?
My System is an ArchLinux with a 3.9.5-1-ARCH kernel.
You are using subprocess.call() incorrectly.
Pass in a list of arguments:
subprocess.call(["/usr/bin/7z", "x", f.name])
The argument is not handled by a shell and is not parsed out like a shell would do. This is a good thing as it prevents a security problem with untrusted command line arguments.
Your other options include using shlex.split() to do the whitespace splitting for you, or, as a last resort, telling subprocess to use a shell for your command with the shell=True flag. See the big warning on the subprocess documentation about enabling the shell.

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