Python / SupProcess / SqlCmd / using -v switch to pass variable - python

Trying really hard to use the -v switch to pass a variable to a SQL script (Python), but can't seem to get the syntax correct. I get the following error:
(Note how it looses the C: from the argument and appends a closing backslash)
[stdout] Sqlcmd: ':\Users\Public\MyProj\Tests\WorkingFolder\Database\"': Invalid argument. Enter '-?' for help.
On the server end, here is my syntax:
FILENAME = N'$(LOCATION)\MyDatabase.mdf'
Below is my code
_varText = 'LOCATION="C:\\Users\\Public\\MyProj\\Tests\WorkingFolder\\Database"'
command_process = SubP.Popen(['sqlcmd','-b', '-E', '-S', _server, '-v', _varText , '-d', _database, '-i', filepath],
stdin = SubP.PIPE, stdout = SubP.PIPE, stderr = SubP.STDOUT, shell = True)

You can try
_varText = 'LOCATION=\"C:\\Users\\Public\\MyProj\\Tests\WorkingFolder\\Database\"'
It is based on recommendation in this section: http://docs.python.org/2/library/subprocess.html#converting-an-argument-sequence-to-a-string-on-windows

Related

Command works on Command Prompt but it does not work when called with subprocess.run() or os.system() in python

Python 3.10.6
Windows 10
I have a python function that executes a DXL script using subsystem.run() or os.system() (whichever works best I guess). The problem is that when I run a custom command using python it does not work, but when I paste the same command in the command prompt, it works. I should also clarify that command prompt is not the ms store windows terminal (cannot run ibm doors commands there for some reason). It is the OG prompt
I need to use both python and IBM Doors for the solution.
Here is a summer version of my code (Obviously, the access values are not real):
#staticmethod
def run_dxl_importRTF():
dquotes = chr(0x22) # ASCII --> "
module_name = "TEST_TEMP"
script_path = "importRTF.dxl"
script_do_nothing_path = "doNothing.dxl"
user = "user"
password = "pass"
database_config = "11111#11.11.1111.0"
doors_path = dquotes + r"C:\Program Files\IBM\Rational\DOORS\9.7\bin\doors.exe" + dquotes
file_name = "LIBC_String.rtf"
# Based On:
# "C:\Program Files\IBM\Rational\DOORS\9.7\\bin\doors.exe" -dxl "string pModuleName = \"%~1\";string pFilename = \"%~2\";#include <importRTF.dxl>" -f "%TEMP%" -b "doNothing.dxl" -d 11111#11.11.1111.0 -user USER -password PASSWORD
script_arguments = f"{dquotes}string pModuleName=\{dquotes}{module_name}\{dquotes};string pFileName=\{dquotes}{file_name}\{dquotes};#include <{script_path}>{dquotes}"
command = [doors_path, "-dxl", script_arguments, "-f", "%TEMP%", "-b", script_do_nothing_path, '-d', database_config, '-user', user, '-password', password]
res = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(f"COMMAND:\n{' '.join(res.args)}")
print(f"STDERR: {repr(res.stderr)}")
print(f'STDOUT: {res.stdout}')
print(f'RETURN CODE: {res.returncode}')
return
PYTHON SCRIPT OUTPUT:
COMMAND:
"C:\Program Files\IBM\Rational\DOORS\9.7\bin\doors.exe" -dxl "string pModuleName=\"TEST_TEMP\";string pFileName=\"LIBC_String.rtf\";#include <importRTF.dxl>" -f %TEMP% -b doNothing.dxl -d 11111#11.11.1111.0 -user USER_TEMP -password PASS_TEMP
STDERR: 'The system cannot find the path specified.\n'
STDOUT:
RETURN CODE: 1
When I run the same command in the command prompt, it works (dxl script is compiled).
I identified the problem which is the script_argument variable. Meaning that, when I try to just enter the IBM Doors server without compiling a DXL script, it works on python and the command prompt.
The python script needs to be dynamic meaning that all of the initial declared variables can change value and have a path string in it. I am also trying to avoid .bat files. They also did not work with dynamic path values
Thanks for your time
I tried:
Changing CurrentDirectory (cwd) to IBM Doors
os.system()
Multiple workarounds
Tried IBM Doors path without double quotes (it doesnt work because of the whitespaces)
.bat files
When calling subprocess.run with a command list and shell=True, python will expand the command list to a string, adding more quoting along the way. The details are OS dependent (on Windows, you always have to expand the list to a command) but you can see the result via the subprocess.list2cmdline() function.
Your problem is these extra escapes. Instead of using a list, build a shell command string that already contains the escaping you want. You can also use ' for quoting strings so that internal " needed for shell quoting can be entered literally.
Putting it all together (and likely messing something up here), you would get
#staticmethod
def run_dxl_importRTF():
module_name = "TEST_TEMP"
script_path = "importRTF.dxl"
script_do_nothing_path = "doNothing.dxl"
user = "user"
password = "pass"
database_config = "11111#11.11.1111.0"
doors_path = r"C:\Program Files\IBM\Rational\DOORS\9.7\bin\doors.exe"
file_name = "LIBC_String.rtf"
script_arguments = (rf'string pModuleName=\"{module_name}\";'
'string pFileName=\"{file_name}\";'
'#include <{script_path}>')
command = (f'"{doors_path}" -dxl "{script_arguments}" -f "%TEMP%"'
' -b "{script_do_nothing_path}" -d {database_config}'
' -user {user} -password {pass}')
res = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(f"COMMAND:\n{' '.join(res.args)}")
print(f"STDERR: {repr(res.stderr)}")
print(f'STDOUT: {res.stdout}')
print(f'RETURN CODE: {res.returncode}')

passing variable value in subprocess.run python

How do I call this variable sd_namesp in subprocess run ?
when I try to do this using below method, I get invalid syntax
I also tried f"{sd_namesp}" that doesn't works either
for seccontent in sec_ver_data:
sd_namesp = seccontent.get("name") + seccontent.get("ition") + str(seccontent.get("version")
largs = ['java','-jar','cli.jar','n','-cf', config_path, '-r', seccontent.get("reg"), '-n', seccontent.get("name"), '-i', seccontent.get("sid"), '-f', sd_namesp]
lresp = subprocess.run(largs, text=True, capture_output=True, check=True)
print(lresp.stdout)
print("end")
You're probably getting a syntax error because it looks like you forgot to close your parenthesis here:
sd_namesp = seccontent.get("name") + seccontent.get("ition") + str(seccontent.get("version"))
Notice the extra parentheses at the end.

SyntaxError: missing ; before statement - Python

Let's say I have this snippet
list_command = 'mongo --host {host} --port {port} ' \
'--username {username} --password {password} --authenticationDatabase {database} < {path}'
def shell_exec(cmd: str):
import subprocess
p = subprocess.call(cmd, shell=True)
return p
Let's say these are the commands I'm trying to run on mongo
use users
show collections
db.base.find().pretty()
If format the string list_command with the appropriate values and pass it to the function with shell=True, it works fine. But I'm trying to avoid it for security purposes.
If I call it with shell=False, I get the following error:
2020-08-31T14:08:49.291+0100 E QUERY [thread1] SyntaxError: missing ; before statement #./mongo/user-01-09-2020:1:4
failed to load: ./mongo/user-01-09-2020
253
Your list_command is a shell command: in particular, it includes input redirection (via < {path}), which is a syntactic feature of the shell. To use it you need shell=True.
If you don’t want to use shell=True, you need to change the way you construct the argument (separate arguments need to be passed as separate items of a list rather than as a single string), and you need to pass the script into the standard input via an explicit pipe, by setting its input parameter:
cmd = ['mongo', '--host', '{host}', '--port', …]
subprocess.run(cmd, input=mongodb_script)
Using input raised the following error: TypeError: init() got an unexpected keyword argument 'input'.
I ended up doing the following:
import subprocess
def shell_exec(cmd: str, stdin=None):
with open(stdin, 'rb') as f:
return subprocess.call(cmd.split(), stdin=f)

Issue specifying parameters to 'pstops' in subprocess.Popen

Issuing this command from the command line:
pdftops -paper A4 -nocenter opf.pdf - | pstops "1:0#0.8(0.5cm,13.5cm)" > test.ps
works fine. I tried to convert this to a parameter list for subprocess.Popen like this:
import subprocess as sp
path = 'opf.pdf'
ps = sp.Popen(
["pdftops",
"-paper", "A4",
"-nocenter",
"{}".format(path),
"-"],
stdout = sp.PIPE)
pr = sp.Popen(
["pstops",
"'1:0#0.8(0.5cm,13.5cm)'"],
stdin = ps.stdout,
stdout = sp.PIPE)
sp.Popen(
["lpr"],
stdin = pr.stdout )
where path is the filename - opf.pdf. This produces error, in the second Popen:
0x23f2dd0age specification error:
pagespecs = [modulo:]spec
spec = [-]pageno[#scale][L|R|U|H|V][(xoff,yoff)][,spec|+spec]
modulo >= 1, 0 <= pageno < modulo
(sic). I suspect the 0x23f2dd0 somehow replaced the 'P'. Anyway, I suspect the problem to be in the page spec 1:0#0.8(0.5cm,13.5cm), so I tried with/without the single quotes, and with (escaped) double quotes. I even tried shlex.quote which produced a very exotic ''"'"'1:0#0.8(0.5cm,13.5cm)'"'"'', but still the same error.
What is causing this?
EDIT As a last resource, I tried:
os.system(("pdftops -paper A4 -nocenter {} - | "
"pstops '1:0#0.8(1cm,13.5cm)' | "
"lpr").format(path))
which works perfectly. I'd still prefer the above Popen solution though.
Think about what the shell does with that argument (or use something like printf '%s\n' to get it to show you). We need to undo the shell quoting and replace it with Python quoting (which happens to be eerily similar):
pr = sp.Popen(
["pstops",
"1:0#0.8(0.5cm,13.5cm)"],
stdin = ps.stdout,
stdout = sp.PIPE)

Subprocess call invalid argument or option not found

I'm trying to call ffmpeg command using subprocess.call() on linux, but I'm unable to get the arguments right. Before hand, I used os.system and it worked, but this method is not recommended.
Using arguments with a dash such as "-i" gets me this error
Unrecognized option 'i "rtsp://192.168.0.253:554/user=XXX&password=XXX&channel=0&stream=0.sdp?real_stream"'.
Error splitting the argument list: Option not found
Using arguments without dash like "i" gets me this error
[NULL # 0x7680a8b0] Unable to find a suitable output format for 'i rtsp://192.168.0.253:554/user=admin&password=&channel=0&stream=0.sdp?real_stream'
i rtsp://192.168.0.253:554/user=XXX&password=XXX&channel=0&stream=0.sdp?real_stream: Invalid argument
Here's the code
class IPCamera(Camera):
"""
IP Camera implementation
"""
def __init__(self,
path='\"rtsp://192.168.0.253:554/'
'user=XXX&password=XXX&channel=0&stream=0.sdp?real_stream\"'):
"""
Constructor
"""
self.path = path
def __ffmpeg(self, nb_frames=1, filename='capture%003.jpg'):
"""
"""
ffm_input = "-i " + self.path
ffm_rate = "-r 5"
ffm_nb_frames = "-vframes " + str(nb_frames)
ffm_filename = filename
if platform.system() == 'Linux':
ffm_path = 'ffmpeg'
ffm_format = '-f v4l2'
else:
ffm_path = 'C:/Program Files/iSpy/ffmpeg.exe'
ffm_format = '-f image2'
command = [ffm_path, ffm_input, ffm_rate, ffm_format, ffm_nb_frames, ffm_filename]
subprocess.call(command)
print(command)
BTW, I'm running this command on a MT7688.
Thanks
You have to split the options:
command = [ffm_path, '-i', ffm_input, '-r', ffm_rate, '-f', ffm_format, '-vframes', ffm_nb_frames, ffm_filename]
The ffm_input, ffm_rate, ffm_format should only contain the value:
ffm_input = self.path
ffm_rate = '5'
ffm_nd_frames = str(nb_frames)
ffm_format = 'v412' if platform.system() == 'Linux' else 'image2'
When you pass a list no parsing is done so -r 5 is taken as a single argument but the program expects you to provide two separate arguments -r followed by 5.
Basically if you put them as a single element in the list it's as if you quoted them on the command line:
$ echo "-n hello"
-n hello
$ echo -n hello
hello$
In the first example echo sees a single argument -n hello. Since it does not match any option it just prints it. In the second case echo sees two arguments -n and hello, the first is the valid option to suppress end of line and as you can see the prompt is printed right after hello and not on its own line.

Categories

Resources