Subprocess no output in windows - subprocess

I need to run an exe file with different parameters and write the output to a file. I tried the following script. After the program is running, the output file is empty. Tell me how to solve this problem
import subprocess
output_f = open('output.txt', 'a')
for i in "abcdefghijklmnopqrstuvwxyz{}_":
for j in "abcdefghijklmnopqrstuvwxyz{}_":
program = 'C:/Users/PC/Desktop/task2 (1).exe ' + i +" " +j;
process = subprocess.Popen(program,stdout=output_f)
code = process.wait()
output_f.close()
print(code)

Related

OSError: This docstring was not generated by Nipype

Hey i am runing the following piece of code:
import nipype.interfaces.spm as spm
realign = spm.Realign()
And getting the following error:
raise IOError("This docstring was not generated by Nipype!\n") from e
OSError: This docstring was not generated by Nipype!
After debugging:
My code:
spm.Realign()
When this runs it uses matlab to run the follwing (base.py lines 217):
mlab.inputs.script = """
if isempty(which('spm')),
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
end;
spm_path = spm('dir');
[name, version] = spm('ver');
fprintf(1, 'NIPYPE path:%s|name:%s|release:%s', spm_path, name, version);
exit;
"""
try:
out = mlab.run()
I run it in Matlab and got :
>> isempty(which('spm'))
ans =
logical
0
>> [name, version] = spm('ver');
fprintf(1, 'NIPYPE path:%s|name:%s|release:%s', spm_path, name, version);
NIPYPE path:C:\Program Files\MATLAB\R2022b\toolbox\spm12\spm12|name:SPM12|release:7771
so as you can see I have result from this script, but when checking the "out" variable here (line 239):
out = sd._strip_header(out.runtime.stdout)
Stdout is "" empty string
So I think the problem is Somehow related to the answer of the script from Matlab, how to fix it ??
Thanks!

Save job output from SDSF into a PDS and using ISPF functions in REXX

We periodically runs jobs and we need to save the output into a PDS and then parse the output to extract parts of it to save into another member. It needs to be done by issuing a REXX command using the percent sign and the REXX member name as an SDSF command line. I've attempted to code a REXX to do this, but it is getting an error when trying to invoke an ISPF service, saying the ISPF environment has not been established. But, this is SDSF running under ISPF.
My code has this in it (copied from several sources and modified):
parse arg PSDSFPARMS "(" PUSERPARMS
parse var PSDSFPARMS PCURRPNL PPRIMPNL PROWTOKEN PPRIMCMD .
PRIMCMD=x2c(PPRIMCMD)
RC = isfquery()
if RC <> 0 then
do
Say "** SDSF environment does not exist, exec ending."
exit 20
end
RC = isfcalls("ON")
Address SDSF "ISFGET" PPRIMPNL "TOKEN('"PROWTOKEN"')" ,
" (" VERBOSE ")"
LRC = RC
if LRC > 0 then
call msgrtn "ISFGET"
if LRC <> 0 then
Exit 20
JOBNAME = value(JNAME.1)
JOBNBR = value(JOBID.1)
SMPDSN = "SMPE.*.OUTPUT.LISTINGS"
LISTC. = ''
SMPODSNS. = ''
SMPODSNS.0 = 0
$ = outtrap('LISTC.')
MSGVAL = msg('ON')
address TSO "LISTC LVL('"SMPDSN"') ALL"
MSGVAL = msg(MSGVAL)
$ = outtrap('OFF')
do LISTCi = 1 to LISTC.0
if word(LISTC.LISTCi,1) = 'NONVSAM' then
do
parse var LISTC.LISTCi . . DSN
SMPODSNS.0 = SMPODSNS.0 + 1
i = SMPODSNS.0
SMPODSNS.i = DSN
end
IX = pos('ENTRY',LISTC.LISTCi)
if IX <> 0 then
do
IX = pos('NOT FOUND',LISTC.LISTCi,IX + 8)
if IX <> 0 then
do
address ISPEXEC "SETMSG MSG(IPLL403E)"
EXITRC = 16
leave
end
end
end
LISTC. = ''
if EXITRC = 16 then
exit 0
address ISPEXEC "TBCREATE SMPDSNS NOWRITE" ,
"NAMES(TSEL TSMPDSN)"
I execute this code by typing %SMPSAVE next to the spool output line on the "H" SDSF panel and it runs fine until it gets to this point in the REXX:
114 *-* address ISPEXEC "TBCREATE SMPDSNS NOWRITE" ,
"NAMES(TSEL TSMPDSN)"
>>> "TBCREATE SMPDSNS NOWRITE NAMES(TSEL TSMPDSN)"
ISPS118S SERVICE NOT INVOKED. A VALID ISPF ENVIRONMENT DOES NOT EXIST.
+++ RC(20) +++
Does anyone know why it says I don't have a valid ISPF environment and how I can get around this?
I've done quite a bit in the past with REXX, including writing REXX code to handle line commands, but this is the first time I've tried to use ISPEXEC commands within this code.
Thank you,
Alan

Setting Up Windows System Variables with Python

I am looking to set up two separate system variables through python, so that both gdal_calc and gdal_translate will work properly on my computer. However, it the pathway's that I have appended and the variables that I have added don't seem to be working properly. Any suggestions?
#!/usr/bin/env python
import subprocess
from subprocess import call
import sys
import os
# make dictionary of environmental variables to set up for gdal_calc and gdal_translate
gdal_env = os.environ.copy()
# modify and add variables for environment so that GDAL runs properly
gdal_env["GDAL_DATA"] = "C:\\Program Files (x86)\\GDAL\\gdal-data"
gdal_env["GDAL_DRIVER_PATH"] = "C:\\Program Files (x86)\\GDAL\\gdalplugins"
gdal_env["PATH"] = gdal_env["PATH"] + ";C:\\Program Files (x86)\\GDAL\\bin"
# Set constants
# The pathway to the images files are nested within the '--outfile=' command
inHVFile = os.path.expanduser('~\\Desktop\\Components\\Float32\\newHV32.img')
outPlacement = os.path.expanduser('~\\Desktop\\Components\\Zeros\\newHVZeros_1.img')
outVFile = '--outfile=' + outPlacement
#calc_cmd_HV = ['gdal_calc.py', '-A', inHVFile, outVFile, '--calc=A+1']
inVHFile = os.path.expanduser('~\\Desktop\\Components\\Float32\\newVH32.img')
outPlacement_1 = os.path.expanduser('~\\Desktop\\Components\\Zeros\\newVHZeros_1.img')
outVFile_1 = '--outfile=' + outPlacement_1
#calc_cmd_VH = ['gdal_calc.py', '-A', inVHFile, outVFile_1, '--calc=A+1']
subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', inHVFile, outVFile, '--calc=A+1'], env=gdal_env)
subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', inVHFile, outVFile_1, '--calc=A+1'], env=gdal_env)
#subprocess.call([sys.executable, 'C:\\Program Files (x86)\\GDAL\\gdal_calc.py','-A', inHVFile, outVFile, '--calc=A+1'])
#subprocess.call([sys.executable, 'C:\\Program Files (x86)\\GDAL\\gdal_calc.py','-A', inVHFile, outVFile_1, '--calc=A+1'])
Environmental variables hold information about where files and programs can be found. When using Python to call commandline programs via subprocess.call or subprocess.Popen, you can specify a set of environmental variables at the time the subprocess is spawned. This is done by passing a dictionary to the env kwarg of call or Popen. If env is not specified, the default environmental variables will be used.
Modifications to the environmental variables stored in os.environ will not persist after the Python session has ended.
To call GDAL programs via subprocess.call, do the following:
import os
import subprocess
import sys
# make dictionary of environmental variables
gdal_env = os.environ.copy()
# modify and add variables
gdal_env["GDAL_DATA"] = "C:\\Program Files (x86)\\GDAL\gdal-data"
gdal_env["GDAL_DRIVER_PATH"] = "C:\\Program Files (x86)\\GDAL\\gdalplugins"
gdal_env["PATH"] = gdal_env["PATH"] + ";C:\\Program Files (x86)\\GDAL\\bin"
# ... do preparation ...
a = "a.tif"
b = "b.tif"
output = "output.tif"
calc_cmd = [sys.executable, 'gdal_calc.py', '-A', a, '-B', b, '--outfile='+output, '--calc=A+B']
# spawn a new subprocess
subprocess.call(calc_cmd, env=gdal_env)

as400 crtcmd command not created in library

I am making my own command, and so far the cl code that processes the .cmd code works just fine on its own. I can call it and send in the parameters and it does exactly what it needs to do, so I'm assuming that the error must be with the .cmd:
CMD 'DISPLAY SYSTEM LEVEL (DSPSYSLVL) NADIA S.C.'
PARM KWD(OUTPUT)
MIN(1)
TYPE(*CHAR) LEN(8)
RSTD(*YES)
VALUES(*MSGLINE *DISPLAY)
PROMPT('OUTPUT FOR SYSTEM LEVEL')
PARM KWD(SOLUTION)
TYPE(*CHAR) LEN(4)
RSTD(*YES)
VALUES(*YES *NO)
DFT(*NO)
PROMPT('TELL ME HOW YOU DID IT')
PARM KWD(SHOWCMD)
TYPE(*CHAR) LEN(4)
RSTD(*YES)
VALUES(*YES *NO)
DFT(*NO)
PROMPT('SHOW COMMAND')
when I run crtcmd and give the appropriate filenames, I get the message "Command DSPSYSLVL not created in library [library name]." with a CPF0201 message.
I'm still fairly new to the whole system, and I'm really not sure what the problem could be. The job log doesn't provide any new information either...
It may just be a transcription issue but the first thing that stands out is the multi-line format without the continuation character (+):
CMD 'DISPLAY SYSTEM LEVEL (DSPSYSL'
PARM KWD(OUTPUT) +
MIN(1) +
TYPE(*CHAR) LEN(8) +
RSTD(*YES) +
VALUES(*MSGLINE *DISPLAY) +
PROMPT('OUTPUT FOR SYSTEM LEVEL')
PARM KWD(SOLUTION) +
TYPE(*CHAR) LEN(4) +
RSTD(*YES) +
VALUES(*YES *NO) +
DFT(*NO) +
PROMPT('TELL ME HOW YOU DID IT')
PARM KWD(SHOWCMD) +
TYPE(*CHAR) LEN(4) +
RSTD(*YES) +
VALUES(*YES *NO) +
DFT(*NO) +
PROMPT('SHOW COMMAND')
Each PARM is a single entity and must be 'continued' if split onto multiple lines.
The CRTCMD command should generate a spooled file containing more details about the errors.
EDIT: Also the maximum length of the CMD prompt is 30 characters.

Running command line silently with VbScript and getting output?

I want to be able to run a program through command line and I want to start it with VbScript. I also want to get the output of the command line and assign it to a variable and I want all this to be done silently without cmd windows popping up. I have managed two things separately but not together. Here's what I got so far.
Run the command from cmd and get output:
Dim WshShell, oExec
Set WshShell = WScript.CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("C:\snmpget -c public -v 2c 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.5.1")
x = oExec.StdOut.ReadLine
Wscript.Echo x
The above script works and does what I want except that cmd pops up for a brief moment.
Here's a script that will run silently but won't grab the output
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\snmpset -c public -v 2c -t 0 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.7.1 i 1", 0, true)
Is there a way to get these two to work together?
Let me give you a background on why I want do to this. I am basically polling a unit every 5-10 minutes and I am going to get the script to email or throw a message box when a certain condition occurs but I don't want to see cmd line popping up all day long on my computer. Any suggestions?
Thanks
You can redirect output to a file and then read the file:
return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close
I have taken this and various other comments and created a bit more advanced function for running an application and getting the output.
Example to Call Function: Will output the DIR list of C:\ for Directories only. The output will be returned to the variable CommandResults as well as remain in C:\OUTPUT.TXT.
CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)
Function
Function vFn_Sys_Run_CommandOutput (Command, Wait, Show, OutToFile, DeleteOutput, NoQuotes)
'Run Command similar to the command prompt, for Wait use 1 or 0. Output returned and
'stored in a file.
'Command = The command line instruction you wish to run.
'Wait = 1/0; 1 will wait for the command to finish before continuing.
'Show = 1/0; 1 will show for the command window.
'OutToFile = The file you wish to have the output recorded to.
'DeleteOutput = 1/0; 1 deletes the output file. Output is still returned to variable.
'NoQuotes = 1/0; 1 will skip wrapping the command with quotes, some commands wont work
' if you wrap them in quotes.
'----------------------------------------------------------------------------------------
On Error Resume Next
'On Error Goto 0
Set f_objShell = CreateObject("Wscript.Shell")
Set f_objFso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1, ForWriting = 2, ForAppending = 8
'VARIABLES
If OutToFile = "" Then OutToFile = "TEMP.TXT"
tCommand = Command
If Left(Command,1)<>"""" And NoQuotes <> 1 Then tCommand = """" & Command & """"
tOutToFile = OutToFile
If Left(OutToFile,1)<>"""" Then tOutToFile = """" & OutToFile & """"
If Wait = 1 Then tWait = True
If Wait <> 1 Then tWait = False
If Show = 1 Then tShow = 1
If Show <> 1 Then tShow = 0
'RUN PROGRAM
f_objShell.Run tCommand & ">" & tOutToFile, tShow, tWait
'READ OUTPUT FOR RETURN
Set f_objFile = f_objFso.OpenTextFile(OutToFile, 1)
tMyOutput = f_objFile.ReadAll
f_objFile.Close
Set f_objFile = Nothing
'DELETE FILE AND FINISH FUNCTION
If DeleteOutput = 1 Then
Set f_objFile = f_objFso.GetFile(OutToFile)
f_objFile.Delete
Set f_objFile = Nothing
End If
vFn_Sys_Run_CommandOutput = tMyOutput
If Err.Number <> 0 Then vFn_Sys_Run_CommandOutput = "<0>"
Err.Clear
On Error Goto 0
Set f_objFile = Nothing
Set f_objShell = Nothing
End Function
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning
that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
Here I found a solution, which works for me:
set wso = CreateObject("Wscript.Shell")
set exe = wso.Exec("cmd /c dir /s /b d:\temp\*.jpg")
sout = exe.StdOut.ReadAll
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
#Mark Cidade
Thanks Mark! This solved few days of research on wondering how should I call this from the PHP WshShell. So thanks to your code, I figured...
function __exec($tmppath, $cmd)
{
$WshShell = new COM("WScript.Shell");
$tmpf = rand(1000, 9999).".tmp"; // Temp file
$tmpfp = $tmppath.'/'.$tmpf; // Full path to tmp file
$oExec = $WshShell->Run("cmd /c $cmd -c ... > ".$tmpfp, 0, true);
// return $oExec == 0 ? true : false; // Return True False after exec
return $tmpf;
}
This is what worked for me in my case. Feel free to use and modify as per your needs. You can always add functionality within the function to automatically read the tmp file, assign it to a variable and/or return it and then delete the tmp file.
Thanks again #Mark!
Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim filepath As String = path + "\" + "your.bat"
' Create the file if it does not exist.
If File.Exists(filepath) = False Then
File.Create(filepath)
Else
End If
Dim attributes As FileAttributes
attributes = File.GetAttributes(filepath)
If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
' Remove from Readonly the file.
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer RO.", filepath)
Else
End If
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
' Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer Hidden.", filepath)
Else
End If
Dim sr As New StreamReader(filepath)
Dim input As String = sr.ReadToEnd()
sr.Close()
Dim output As String = "#echo off"
Dim output1 As String = vbNewLine + "your 1st cmd code"
Dim output2 As String = vbNewLine + "your 2nd cmd code "
Dim output3 As String = vbNewLine + "exit"
Dim sw As New StreamWriter(filepath)
sw.Write(output)
sw.Write(output1)
sw.Write(output2)
sw.Write(output3)
sw.Close()
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
Else
' Hide the file.
File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
Console.WriteLine("The {0} file is now hidden.", filepath)
End If
Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
procInfo.WindowStyle = ProcessWindowStyle.Minimized
procInfo.WindowStyle = ProcessWindowStyle.Hidden
procInfo.CreateNoWindow = True
procInfo.FileName = path + "\" + "your.bat"
procInfo.Verb = "runas"
Process.Start(procInfo)
it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes
and after that set the "hidden" attributes to file after writing your cmd code
and run it silently and capture all output saves it to file
so if u wanna save all output of cmd to file just add your like this
code > C:\Users\Lenovo\Desktop\output.txt
just replace word "code" with your .bat file code or command and after that the directory of output file
I found one code recently after searching alot
if u wanna run .bat file in vb or c# or simply
just add this in the same manner in which i have written