How to execute a batch file? [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
SET subkey1=%random%%random%%random%%random%%random%%random%
SET subkey1=%subkey1:0=a%
SET subkey1=%subkey1:1=b%
SET subkey1=%subkey1:2=c%
wmic computersystem where caption="%MYVAR%" rename %subkey1%
This is block of code run in Windows BATCH file, I'd like to adapt it for Python app but I can't think of a way to do so.
I've used:
os.system('cmd xxxx')
to run single line of code, but I don't think this will solve my issue with big block of code that can't be run separately.

below is a way to do it (creating the script on the fly)
import os
script = '''FOR /F "usebackq" %%i IN (`hostname`) DO SET MYVAR=%%i
SET subkey1=%random%%random%%random%%random%%random%%random%
SET subkey1=%subkey1:0=a%
SET subkey1=%subkey1:1=b%
SET subkey1=%subkey1:2=c%
wmic computersystem where caption="%MYVAR%" rename %subkey1%'''
with open('script.cmd', 'w') as f:
f.write(script)
os.system('script.cmd')

Related

Python - IndexError: list index out of range while running python code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Please I need assistance with this code. I keep getting the error message above on line 5 and 35 of the code shown below. What is wrong?
output = sys.argv[1]
main()
sys.argv returns:
The list of command line arguments passed to a Python script. argv[0]
is the script name
So, if you execute the script like this python script.py then sys.argv[0] returns script.py which is the name of script.
As there is no other argument, hence calling sys.argv[1] will raises as IndexError
Now consider another scenario when you execute the script as python script.py tom:
In this case calling sys.argv[1] returns the first command line argument which is tom.
Hope, this helps clear your understanding.
you need to pass argument by running file name like below
python file_name arg1
then only it will work

Prevent python script to run without user input any optional argument [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Have a python script and using argparse I define some optional arguments that could be given by the user before running the script. I wish to not allow the script to run if the user does not enter any of the optional parameters defined (python example.py -> to give an error message). Any idea on how to do this?
You can use an if statement with an expression that uses the any function on all the values of the argument namespace to test if any of the options is given, and if not, print the usage and exit:
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a')
parser.add_argument('-b')
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_usage()
sys.exit()
First answer is pretty good.
Or you could use a simlpe if at the begining of the script.
import sys
if (len(sys.argv) < x):
sys.exit("error message here")
where x is the amount of parameters you are looking for.
Otherwise u can use argparser or manually check like
argv[2] == "-b"

how to run python with args in python code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to write a program in Python that scan files and then insert it into the command
when i try to run "python submit.py path/arg" i get an error.
i tried many commands without success (os.system,os.Popen,subprocess.call,exec)
Thanks in advance
this is my program:
#!/usr/bin/python
import os
import glob
import subprocess
import commands
import time
import threading
exe = []
os.chdir("/home/malwares")
exe = glob.glob('*.exe')
exe1 = ''.join(exe)
exe1 = exe1.replace("']", "")
exe1 = exe1.replace("['", "")
os.chdir("/home/utils/")
//here i tried to run python script with args
subprocess.call(["python", "submit.py", "/home/malwares",exe1])
I'm confused by your calls to str.replace. Why would you have a filename with ['] in it? But okay, fair enough, let's at least do it right then....
os.chdir('/home/malwares')
exe = glob.glob('*.exe') # no need to initialize this first.
exe_str = ''.join(exe) # name it a little more descriptively than exe1
trans_table = str.maketrans('', '', "[']")
exe_str = exe_str.translate(trans_table)
# this is probably faster than
# ''.join( [filename.translate(trans_table) for filename in glob.glob('*.exe')] )
# but you may want to profile it
subprocess.call( ['python', 'submit.py', '/home/malwares', exe_str] )
# is this REALLY what you want??? This will do:
# >> python submit.py /home/malwares FILEONE.exeFILETWO.exeFILETHREE.exe
# maybe you should have used ' '.join(exe) instead?

writing os.system output to file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
basically, I want to output the os.system results to a file based on sys.argv input. See below for the code. It throws me the error: SyntaxError: invalid syntax. My guess is that the output operator > does not accept variables?
#!/usr/bin/python
import os
import sys
nfile = sys.argv[1]
intfile=('/folder/folder/%s/%s.txt' % (nfile, nfile))
if os.path.isfile(intfile): # if file exist remove
os.remove(intfile)
else:
os.system('sudo ovs-vsctl list-ports %s > %s' % (nfile, intfile)
os.system is frowned upon. The subprocess module is cleaner, safer and as powerful as os.system().
import subprocess
with open(intfile, 'w') as outfile:
subprocess.call(['sudo', 'ovs-vsctl', 'list-ports', nfile], stdout=outfile)

Bind and execute python script [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
How do I bind a python script to a file, and it runs on the background when the file is opened?
Lets say I want to bind a file to a photo and then the photo is closed or open the script runs
In Windows (for example), you could associate the file type (not one particular file, but all files with a certain extension) with the python script, and then launch the photo viewer (with the filename as argument, so that the application opens this file) from within the python script. This way, both your script and the "main" application will be run when opening the file type.
BTW: In your script you could test the filename for certain patterns or substrings, to do different actions with different files of this file type...
This solution may not be as smooth as you'd hope, but it probably could do as a "workaround".
Check this question (rather it's answers), and this answer,
And in-case you don't want to do so much reading (though you should),
What you might need is to use:
os.startfile() on Windows
subprocess.call(['open',..]) on Mac
subprocess.call(['xdg-open', ...]) on *nix
Which come to something like:
import platform, os, subprocess
#....
def nix_open(filename):
pass # I don't know this one, you can research
def win_open(filename):
return os.startfile(filename)
def mac_open(filename):
return subprocess.call(['open',filename])
def handle_open(filename):
s_name = platform.system()
if s_name in ('Linux','Unix'):
return nix_open(filename)
elif s_name == 'Windows':
return win_open(filename)
elif s_name == 'Darwin':
return mac_open(filename)
# ...
else:
raise EnvironmentError, 'OS not supported'

Categories

Resources