I have a line of Powershell script that runs just fine when I enter it in Powershell's command line. In my Python application which I run from Powershell, I am trying to send this line of script to Powershell.
powershell -command ' & {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}'
I know that the script works because I've been able to implement it on its own from the Powershell command line. However, I haven't been able to get Python to send this line to the shell without getting a "non-zero exit status 1."
import subprocess
product = "765377"
scriptPath = "./uploadImageToBigcommerce.ps1"
def process_image(sku, fileType, searchDirectory, destinationPath, scriptPath):
psArgs = "Process-Image '"+sku+"' '"+fileType+"' '"+searchDirectory+"' '"+destinationPath+"'"
subprocess.check_call([create_PSscript_call(scriptPath, psArgs)], shell=True)
def create_PSscript_call(scriptPath, args):
line = "powershell -command ' & {. "+scriptPath+"; "+args+"}'"
print(line)
return line
process_image(product, ".jpg", "C:\Images", "C:\webDAV", scriptPath)
Does anyone have any ideas to help? I've tried:
subprocess.check_call()
subprocess.call()
subprocess.Popen()
And maybe it is just a syntax issue, but I haven't been able to find enough documentation to confirm that.
Using single quotes inside a single quoted string breaks the string. Use double quotes outside and single qoutes inside or vice versa to avoid that. This statement:
powershell -command '& {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}'
should rather look like this:
powershell -command "& {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}"
Also, I'd use subprocess.call (and a quoting function), like this:
import subprocess
product = '765377'
scriptPath = './uploadImageToBigcommerce.ps1'
def qq(s):
return "'%s'" % s
def process_image(sku, fileType, searchDirectory, destinationPath, scriptPath):
psCode = '. ' + scriptPath + '; Process-Image ' + qq(fileType) + ' ' + \
qq(searchDirectory) + ' ' + qq(destinationPath)
subprocess.call(['powershell', '-Command', '& {'+psCode+'}'], shell=True)
process_image(product, '.jpg', 'C:\Images', 'C:\webDAV', scriptPath)
Related
I am a newbie to python and i am having issues in having the output of shell command assigned to variable.
I have a python script which runs shell script cmd line and output something like below
Name: test
Version: i22349
I want to use this output as input for next operation. How can i assign a variable with the outputted value. Could someone help me with this.
Here is the code which i am using
import os
deploymentName = 'testdeployment'
myCmd = 'list dep ' + deploymentName + ' | egrep "^Version|Deck Name"'
print ("Fetching the Deck details - Running Command - " + myCmd)
os.system(myCmd)
Currently it returns output as ,
Name: test
Version: i22349
How do i get the value test and i22349 assigned to 2 variables inside the python code ?
I'm attempting to rsync some files with pexpect. It appears the glob string argument I'm providing to identify all the source files is not working.
The gist of it is something like this...
import pexpect
import sys
glob_str = (
"[0-9]" * 4 + "-" +
"[0-9]" * 2 + "-" +
"[0-9]" * 2 + "-" +
"[A-B]" + "*"
)
SRC = "../data/{}".format(glob_str)
DES = "user#host:" + "/path/to/dest/"
args = [
"-avP",
SRC,
DES,
]
print "rsync" + " ".join(args)
# Execute the transfer
child = pexpect.spawn("rsync", args)
child.logfile_read = sys.stdout # log what the child sends back
child.expect("Password:")
child.sendline("#######")
child.expect(pexpect.EOF)
Fails with this...
building file list ...
rsync: link_stat "/Users/U6020643/git/ue-sme-query-logs/code/../data/[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]\-[A-B]*" failed: No such file or directory (2)
0 files to consider
...
The same command run in the shell works just fine
rsync -avP ../data/[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]\-[A-B].csv username#host:/path/to/dest/
The pexpect documentation mentions this
Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell.
But doing so...
...
args = [
"rsync",
"-avP",
SRC,
DES,
]
...
child = pexpect.spawn("/bin/bash", args) # have to use a shell for glob expansion to work
...
Runs into a permissions issue
/usr/bin/rsync: /usr/bin/rsync: cannot execute binary file
To run rsync with bash you have to use bash -c "cmd...":
args = ["-c", "rsync -avP {} {}".format(SRC, DES)]
child = pexpect.spawn('/bin/bash', args=args)
And I think you can also try rsync --include=PATTERN.
OK this task seems to be really easy to do. However I spent a couple of hours without any results.
User have:
7z
Windows
R
User should enter:
path to 7z (z7path)
filename
System should unpack rar into the project's root
I tried:
cmd = "C:\\Program Files (x86)\\7-Zip\\7z e D:/20140601.rar"
system(shQuote(cmd))
And..nothing happens.
Please don't advise to set up PATH, it doesn't help, and this should work without it.
Ok, I finally got it.
Use shell
Use shQuote for surrounding path
Use right keys
z7path = shQuote('C:\\Program Files (x86)\\7-Zip\\7z')
file = paste(getwd(), '/101-01.rar', sep = '')
cmd = paste(z7path, ' e ', file, ' -y -o', getwd(), '/', sep='')
shell(cmd)
I had to modify the code from the second answer, and finally it works.
You can change "-ir!. -o" by "-y -o" if you want all files.
z7path = shQuote('C:\\Program Files\\7-Zip\\7z')
file = paste('"', 'D:/20140601.rar', '"',sep = '')
cmd = paste(z7path, ' e ', file, ' -ir!*.* -o', '"', getwd(), '"', sep='')
system(cmd)
I coded a python script that creates a windows batch file which bates stamps PDF files.
The batch program runs just fine, if open/run it in Windows, e.g., by selecting it and hitting Enger.
But when I try to run subprocess on the batch file, I get the following error message:
Traceback (most recent call last):
File "C:\Apps\UtilitiesByMarc\bates_stamp_pdf_files_using_veryPDF_and_regex_match_groups_and_verbose_.py", line 56, in <module>
RetVal = subprocess.call(target_file_fullname, shell=False)
File "C:\Python27\lib\subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
I can't figure out how to run subprocess in a way that would prevent the error message from occurring. Any suggestions would be much appreciated, especially references to an explanation of the problem.
Here's the python code:
# -*- coding: latin-1 -*-
# bates_stamp_pdf_files_using_veryPDF_.py
import os
import sys
import re
import time
import subprocess
exhibits_temp_dir = r'\\Hpquadnu\c\Svr1\K\data\Steinberg Nisan\Scans.Steinberg Nisan\Exhibits.Temp'
stamp_prg = r'"C:\Apps\pdfstamp_cmd_veryPDF\pdfstamp.exe"'
# DOES NOT WORK; VERBOSE MB DONE IN THE COMPILE STATEMENT srchptrn = (r"""([exEXapAPatAT]{2,3}_?) # Ex or Att or App, etc.
# ([0-9]+) # Seq. no of the document
# ([^0-9]+.+) # a non-digit character to separate the seq. no from other identifying chars.""", re.X)
srch_or_match_obj = re.compile(r"""([exEXapAPatAT]{2,3}_?) # Ex or Att or App, etc.
([0-9]+) # Seq. no of the document
([^0-9]+.+) # a non-digit character to separate the seq. no from other identifying chars.""", re.X)
target_file_fullname = exhibits_temp_dir + '\\' + 'bates_stamp.bat'
target_file_objname = open(target_file_fullname, 'w')
dirlist = os.listdir(exhibits_temp_dir)
for item in dirlist:
matches_obj = srch_or_match_obj.search(item)
if matches_obj:
item_no = str(matches_obj.group(2))
file_fullname = '"' + os.path.join(exhibits_temp_dir, item) + '"'
#Cmdline = stamp_prg -PDF "example.pdf" -o "marc_2013-06-12_AM_09-51-54_.pdf" -AT "Exhibit 1, page \p" -P5 -MLR-20 -FN301 -MTB-20
Cmdline = stamp_prg +' -PDF ' + file_fullname + ' -o ' + file_fullname + ' -AT "Exhibit ' + item_no + ', page \p" -P5 -MLR-20 -FN301 -MTB-20'
print Cmdline + '\r\n'
text2write = Cmdline + '\r\n'
target_file_objname.write(text2write)
target_file_objname.write('\n\n')
else:
print 'Not matched: ' + item
text2write = 'pause'
target_file_objname.write(text2write)
target_file_objname.close
time.sleep(1)
RetVal = subprocess.call(target_file_fullname, shell=False)
print 'Reval = ' + RetVal
print 'Job done'
Apparently you file is not closed when you run it. Maybe the parenthesis (bracket) :
target_file_objname.close()
I am trying to implement a hash function and here is my code:
import BitVector
import glob
path = '/home/vguda/Desktop/.txt'
files=glob.glob(path)
hash = BitVector.BitVector(size = 32)
hash.reset(0)
i = 0
for file in files:
bv = BitVector.BitVector( filename = file )
while 1 :
bv1 = bv.read_bits_from_file(8)
if str(bv1) == "":
break
hash[0:8] = bv1 ^ hash[0:8]
hash >> 8
i = i+1
hash_str = ""
hash_str = str( hash )
text_file = open("/home/vguda/Desktop/result.txt ","w")
text_file.write("Hash Code is %s" %hash_str)
text_file.close()
print hash
print (i)
The displayed error is:
"bash: syntax error near unexpected token `('
First, perhaps this happened in copy and paste, but your indenting in your loop is all messed up, I'm not sure which blocks go where.
When you run things in the shell, you need to either tell python to run it:
python myscript.py
Or, put the following line as the first thing in your program to tell bash to run it as a python program:
#!/usr/bin/python
Currently, bash is trying to run your python program as a bash script, and obviously running into syntax errors.