I need to run an executable file that works only with command prompt multiple times.It is used to retrieve data Information based on the Details of the framenumbers and it ranges only between 0 to any postive value. And I have this framenumber data in a Excel file and i want it to loop through the range of framenumber. This is the part of command --start {framenumber1} --end {framenumber2} where it should be changed for each execution. i also Need admin rights to run this executable.
Is there any possible way of automating this workflow in python for using the command prompt multiple times with slightly different Input? Any Suggestion would be very helpful
Found the solution of using os.system() invoking to solve it. Here is the gist of code of how to Access the command prompt using python with admin Rights.
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
df=pd.read_excel(r'D:\final_xxxx.xlsx',sep=',')
for i,x in zip(df['framenumber'],df['C']):
os.chdir(os.path.dirname(os.path.abspath(r'C:\Users\xxxx\Desktop\xxxxxxx\xxxv1.02\xxx\xxx.exe')))
if i==i:
k=math.trunc(i)
j=k
#executable operation running in python for command prompt till the loop ends
os.system(r'xxxx.exe --file "D:\xxxx\2020-07-27_xxxxx.xxxx" --output "D:\xxxx" --start {} --end {}'.format(j,j))
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
Related
I have a python script that does a zipping of a few files. For zipping the files with a password I use os.system() function and pass my zipping command ie. zip -j -re <file_path> <to_path>. This command asks for a password on the terminal which I have to put manually on the terminal like this.
Enter password:
Verify password:
I want to hardcode my password and pass it when the terminal asks for a password.
I tried to send the passwords using os.system(password) twice thinking that it will take it but it did not work.
cmd = "zip -j -re {} {}".format(DUMPSPATH,TEMPPATH)
passwrd = 'hello123'
os.system(cmd)
os.system(passwrd)
os.system(passwrd)
How do I send arguments using python to fill passwords automatically?
When you call os.system(), you are sending a command to your shell to run. So calling os.system(passwrd) is sending your password as a standalone command to be run by the shell, which is not what you want here.
The zip program features a -P password argument that allows you to specify the password to encrypt zip files when you initially run the command without having to manually input it for batch jobs. So essentially your code should be changed to something like this:
passwrd = 'hello123'
cmd = "zip -j -re -P {} {} {}".format(passwrd, DUMPSPATH,TEMPPATH)
os.system(cmd)
Another side note, it's recommended to use the subprocess module instead of resorting to os.system, so take a look at subprocess.Popen if you get a chance.
It's nice computer_geek has found the correct command line argument (I can't see it listed over here, but it works), but I absolutely HAVE to post my ludicrous solution (for posterity). NOTE - requires xdotool installed on your system.
import subprocess
DUMPSPATH = ""
TEMPPATH = ""
pwd = "lala"
zipper = subprocess.Popen(['zip','-j','-re',DUMPSPATH,TEMPPATH])
subprocess.run(['xdotool','type',pwd])
subprocess.run(['xdotool','key', 'Return'])
subprocess.run(['xdotool','type',pwd])
subprocess.run(['xdotool','key', 'Return'])
zipper.wait()
I have written a python program that needs a first command line argument to run from the Terminal. The program can be used to copy a text to the clipboard when it is run with a certain keyword.
~ python3 mclip.py 'agree'
This use case is just an exercise to understand, how I can run a batch file on macOS (or shell script in macOS terminology).
I have created the following shell script and saved it as mclip.command:
#!/usr/bin/env bash
python3 /Users/Andrea_5K/mclip.py
My idea is to execute my shell script from the spotlight input window, passing the argument 'agree'. How can I do that?
On windows the batch file would look like that (mclip.bat):
#py.exe C:\path_to_my_file\mclip.py %*
#pause
I can press WIN-R and type mclip *argument* to run the program. But how can I do the same on a Mac? I cannot type mclip agree in spotlight, that doesn't work like in WIN-R.
#! python3
# mclip.py - A multi-clipboard program.
TEXT = {
'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""",
'upsell': """Would you consider making this a monthly donation?""",
}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python mclip.py [keyphrase] - copy phrase text')
sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT:
pyperclip.copy(TEXT[keyphrase])
print('Text for ' + keyphrase + ' copied to clipboard.')
else:
print('There is no text for ' + keyphrase)
I can get Spotlight to run a script which:
offers you a dialog box with your three options and
then runs your Python script passing the selected option
But I cannot get Spotlight to pass an option to a Python script directly. If that helps, here's how to do it.
Start Script Editor and enter the following code, save it as an app called mclip:
set theArg to choose from list {"Agree", "Busy", "Upsell"} with title "Chooser Dialog" with prompt "Choose option"
tell application "Terminal"
do shell script "/Users/YOURNAME/mclip.py " & theArg
end tell
Note that adding on run argv at the top still doesn't get you any arguments you add within Spotlight - it just plain doesn't seem to want to pass on any arguments you type in the Spotlight dialog.
Now write a Python script called $HOME/mclip.py:
#!/usr/bin/env python3
import os, sys
# Just write the received parameter into a text file on the Desktop to show how it works
file = os.path.expanduser("~/Desktop/result.txt")
with open(file, 'w') as f:
f.write(sys.argv[1])
And make it executable (just necessary one time) with:
chmod +x $HOME/mclip.py
If you now use Spotlight to run mclip, it will pop up a dialog like this:
You may have to answer security questions the first time you run it - depending on your macOS version.
Note that if all your Python script does is copy some text onto the clipboard, you can do that without Python within the Applescript above using:
set the clipboard to "Some funky text"
Just a detail: python is case sensitive. So, if the keys of the dictionary are lower case, the list values in the apple script ought to be lower case to `:D
Assume the shell script (mapIt.command) is:
#!/usr/bin/env bash
python3 /path/to/my/pythonScript.py $#
The $# is interpreted as a list of command line arguments.
I can run the shell script in the MacOS Terminal like that:
sh mapIt.command Streetname Number City
The command line arguments Streetname Number City are forwarded to the python script.
I am using Python 2.7.5, since this version is installed on the machine which I want to run script.
I have created a simple GUI in Tkinter, with button and text input.
Now in one input I provide the ip, or hostname of server, in next step I read the value of input fields and send it to linux bash terminal, and here I have a problem.
Reading the value from input field(works good)
nazwa_ip = self.Input_IP_hostname.get("1.0", 'end-1c')
and next:
os.system('gnome-terminal --window-with-profile=MY_PROFILE -e "ssh -t user_name#nazwa_ip"')
and here is the problem, because it wont change "nazwa_ip" to the read value. That comand send to terminal:
ssh -t user_name#nazwa_ip
but i want to send:
ssh -t user_name#ip_adres_from_input_field
Can somebody help me to resolve the issue?
according to the Python docs, it is recommended that os.system be replaced with the subprocess module .
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
String formatting will work here:
os.system('gnome-terminal --window-with-profile=MY_PROFILE -e "ssh -t user_name#%s"' % nazwa_ip)
Using the subprocess method might be better to do this.
import subprocess
nazwa_ip = self.Input_IP_hostname.get("1.0", 'end-1c')
ssh_param = "ssh -t user_name#{}".format(nazwa_ip)
subprocess.call(['gnome-terminal', '--window-with-profile=MY_PROFILE', '-e', ssh_param])
Whilst running a subprocess is easy, starting one in a graphical terminal that behaves exactly like one the user launched is a little tricker. You could use my program interminal (link), which basically does what Stephen Rauch's answer does with gnome-terminal, but via a shell so that user environment variables and aliases etc are all available, which could be useful on the offchance that they affect how ssh runs.
You would use it from Python like this:
import subprocess
subprocess.Popen(['interminal', 'ssh', '-t', 'username#{}'.format(ip_address)])
I am looking for a way to execute multiple commands in the same shell instance using a separate function for each, something that I can define when the shell process opens/closes and can pass commands to.
so far all the answers I have found have only been in a single function
ie:
#!/usr/bin/env python
from subprocess import check_call
check_call(r"""set -e
ls -l
<some command> # This will change the present working directory
launchMyApp""", shell=True)
I need the same effect but with each command in a different function like
shell.open()
shell.exec("dir")
shell.exec("cd C:/Users/" + User + "/Desktop)
shell.close()
if you are wondering whyyy it has to be separate the command to run is coming from user input. yes I realize that is a security risk, but security isn't a problem in this case, as its purely an educational venture and not going to be used for anything
you could use subprocess.check_call(cmds_str, shell=True) in conjunction with multiple commands in the same line: How to run two commands in one line in Windows CMD?
You could build each command individually and add them to a list, and then use ' & '.join(cmd_list) to get cmds_str.
I don't use Windows but it works on Linux.
You can try pexpect with cmd.exe
import pexpect
child = pexpect.spawn("cmd.exe")
child.expect_exact("> ")
#print(child.before.decode('utf-8'))
print(child.before)
child.sendline("dir")
child.expect_exact("> ")
print(child.before)
child.sendline("cd C:/Users/" + User + "/Desktop")
child.expect_exact("> ")
print(child.before)
It runs cmd.exe, sends command in child.sendline() and looks for prompt child.expect_exact("> ") to get all text generated by command child.before.
I am trying to remotely execute a simple python script userinfo.py present in remotehost.
Below is sourcecode of userinfo.py [ using Python 2.7.10 ]
#############
print "Userinfo :"
name=raw_input("Enter your name")
age=raw_input("Enter your age")
print "Name"+name+"\nAge"+age
#############
But script is working abnormally when run remotely.
[user#localhost]# ssh remotehost python /home/userinfo.py
Userinfo :
Enter your nameEnter your ageName
Age
[user#localhost]#
Execution summary ::
During execution, it doesn't print anything, it directly waits for user input and I just pressed Enter key it will display output as above.
Would like to know why it is not behaving as expected when raw_input is used.
When values are passed as arguments, it works fine.
[user#localhost]# ssh remotehost python userinfo.py xyz 20
Userinfo :
Name xyz
Age 20
[user#localhost]#
below is changed code.
###########
import sys
print "Userinfo :"
name=sys.argv[1]
age=sys.argv[2]
print "Name "+name+"\nAge "+age
############
Would like to know why interactive way is not working as expected and what may be fix.
In a regular terminal, the raw_input prompt is flushed immediately, meaning you will see the prompt "Enter Your Name".
If you run this script through ssh, it saves the output until the script it finished and only then prints everything in the buffer.
What you need is to run python unbuffered, which will force stdout to flush after every output, and thus display to your ssh session. This can be accomplished several ways.
ssh user#remotehost python -u script.py
or make the file executable and unbuffered by adding the following to top of your .py script. Be sure to use your actual python path here:
#! /usr/bin/python - u
and then in make it executable
sudo chmod +x script.py
then
ssh user#remotehost ./script.py