Opening A Program With A Python Script - python

I am trying to get a script to open the "Stellarium" application on my laptop, but it keeps giving me this error...
"Windows cannot find "stellarium.exe." Make sure you typed the name correctly, and then try again."
I am guessing something is wrong with the "prog =" syntax.
Here are files' locations...
C:\Stellarium\Stellarium.exe
C:\Stellarium\Scripts\StartUp.ssc
Double-clicking either the script file or the *.exe will open The Stellarium application as expected.
Here is the code...
stellocation = "C:\\Stellarium"
...
prog = "start /d ""+stellocation+"" stellarium.exe --startup-script startup.ssc"
os.system(prog)
sys.exit()

I think you messed up the + and the ". You effectively call
'start /d +stellocation+ stellarium.exe --startup-script startup.ssc'
Try
prog = "start /d " +stellocation+ " stellarium.exe --startup-script startup.ssc"
or even better: use subprocess.run:
import subprocess
subprocess.run(['start', '/d', stellocation, 'stellarium.exe', '--startup-script', 'startup.ssc'])
I have no windows around, so I did not try.

did you change the directory using os.chidr(location of files) first? I think that's why it can't see the exe file.

Related

C# args[] parameter about path with space on python code

I made some c# program and I tried to use c# program on Python.
C# program is CLI and use by CMD.
On CMD prompt I can use my program like below command
test.exe "C:\Users\Downloads\test file\1.txt" "C:\Users\Downloads\test file\2.txt"
But when I tried on python code.
AUDIO_TOOL = r"C:/Users/Downloads/test.exe"
filepath = r"C:/Users/Downloads/test file/1.txt"
binary_file_path = r"C:/Users/Downloads/test file/2.txt"
subprocess.call(["%s" % AUDIO_TOOL, r"%s" % filepath, r"%s" % binary_file_path], shell=True)
path that without space work properly but path with space does not work at all.
please help me.
You have to enclose the whole command in quotation marks
this How do I use spaces in the Command Prompt? may be help you

Learn Python the Hard Way, Ex 2; Powershell not outputting ex1.py?

I am very new to the language so I might need an ELI5 for the response.
I've created my ex1.py, checked all of the casing and syntax and it appears to be right?
print "Hellow World!"
print "Hello again"
print "i like typing this"
print "this is fun"
print 'Yay! printing!'
print "I'd much rather you 'n'."
print 'I "said" do not touch this!'
When I type: python ex1.py in terminal after navigating to the proper folder, the terminal displays the script, not powershell.
I've tried entering
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
etc. string that is on page 8 of the book into PowerShell, but that doesn't seem to help.
In the filepath above, should I be replacing C:\Python27 with the literal filepath of where i have Python installed? Likewise, "User" with my username? Or do I enter the string literally as is?
Your code is fine but it seems your environment is not set correctly. Do the following:
Start powershell
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\<directory_where_python.exe in installed>", "User")
Restart powershell (close it, then start it back up again)
Cd in directory that contains ex1.py
Execute python .\ex1.py
Please see if you have saved the file ex1.py properly.Check once.
You may have saved the file name first and later typed in the notepad and forgot to save the file.

Call a cmd.exe bat.-like command with python

i need some help with this...
I have a program installed on my computer that i want to call to calculate some things and give me an output-file...
in Matlab the command "dos()" does the job giving me also the cmd screen output in matlab.
I need this to work in python but i am making something wrong.
data='file.csv -v'
db=' -d D:\directory\bla\something.db'
anw='"D:\Program Files\bla\path\to\anw.exe"' + db + ' -i' + data
"anw" output is this one:
>>> anw
'"D:\\Program Files\\bla\\path\\to\\anw.exe" -d D:\\directory\\bla\\something.db -i file.csv -v'
## without the "" it does not work either
import subprocess as sb
p= sb.Popen('cmd','/K', anw) ## '/C' does not work either
i get the following error message from cmd.exe inside the python shell
Windows cannot find "\"D:\Program Files\bla\path\to\anw.exe"" Make sure you typed the name correctly, and then try again.
this line runs when i make a bat. file out of it.
it runs in matlab via "dos(anw)" so what is wrong here?
ps: i have blanks in my command... could this be the problem? i do not know where the first "\" comes from in the cmd. exe error message
for now i created a bat. file with all the stuff cmx.de should do in the specific directory where the input file lies...
i just had to tell python to change directory with
import os
os.chdir("D:\working\directory")
os.system(r'D:\working\directory\commands.bat')
it works good and gives me the output of cmd directly in the python shell

Disable 'pause' in windows bat script

In windows, I am running a bat script that currently ends with a 'pause' and prompts for the user to 'Press any key to continue...'
I am unable to edit the file in this scenario and I need the script to terminate instead of hang waiting for input that will never come. Is there a way I can run this that will disable or circumvent the prompt?
I have tried piping in input and it does not seem to help. This script is being run from python via subprocess.Popen.
Try to execute cmd.exe /c YourCmdFile < nul
YourCmdFile - full path to your batch script
subprocess.call("mybat.bat", stdin=subprocess.DEVNULL)
Would call mybat.bat and redirect input from nul on windows (which disables pause as shown in other answers)
This one turned out to be a bit of a pain. The redirect of nul from Maximus worked great, thanks!
As for getting that to work in python, it came down to the following. I started with:
BINARY = "C:/Program Files/foo/bar.exe"
subprocess.call([BINARY])
Tried to add the redirection but subprocess.call escapes everything too well and we loose the redirect.
subprocess.call([BINARY + " < nul"])
subprocess.call([BINARY, " < nul"])
subprocess.call([BINARY, "<", "nul"])
Using shell=True didn't work because the space in BINARY made it choke trying to find the executable.
subprocess.call([BINARY + " < nul"], shell=True)
In the end, I had to resort back to os.system and escape myself to get the redirection.
os.system(quote(BINARY) + " < nul")
Not ideal, but it gets the job done.
If anyone knows how to get the last subprocess example to work with the space in the binary, it would be much apprecated!
For me the following code works:
p = Popen("c:\script.bat <nul", cwd="c:\")

running a system command in a python script

I have been going through "A byte of Python" to learn the syntax and methods etc...
I have just started with a simple backup script (straight from the book):
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My Documents"', 'C:\\Code']
# Notice we had to use double quotes inside the string for names with spaces in it.
# 2. The backup must be stored in a main backup directory
target_dir = 'E:\\Backup' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
Right, it fails. If I run the zip command in the terminal it works fine. I think it fails because the zip_command is never actually run. And I don't know how to run it.
Simply typing out zip_command does not work. (I am using python 3.1)
Are you sure that the Python script is seeing the same environment you have access to when you enter the command manually in the shell? It could be that zip isn't on the path when Python launches the command.
It would help us if you could format your code as code; select the code parts, and click on the "Code Sample" button in the editor toolbar. The icon looks like "101/010" and if you hold the mouse pointer over it, the yellow "tool tip" box says "Code Sample <pre></pre> Ctrl+K"
I just tried it, and if you paste code in to the StackOverflow editor, lines with '#' will be bold. So the bold lines are comments. So far so good.
Your strings seem to contain backslash characters. You will need to double each backslash, like so:
target_dir = 'E:\\Backup'
This is because Python treats the backslash specially. It introduces a "backslash escape", which lets you put a quote inside a quoted string:
single_quote = '\''
You could also use a Python "raw string", which has much simpler rules for a backslash. A raw string is introduced by r" or r' and terminated by " or ' respectively. examples:
# both of these are legal
target_dir = r"E:\Backup"
target_dir = r'E:\Backup'
The next step I recommend is to modify your script to print the command string, and just look at the string and see if it seems correct.
Another thing you can try is to make a batch file that prints out the environment variables, and have Python run that, and see what the environment looks like. Especially PATH.
Here is a suggested example:
set
echo Trying to run zip...
zip
Put those in a batch file called C:\mytest.cmd, and then have your Python code run it:
result_code = os.system("C:\\mytest.cmd")
print('Result of running mytest was code', result_code)
If it works, you will see the environment variables printed out, then it will echo "Trying to run zip...", then if zip runs it will print a message with the version number of zip and how to run it.
zip command only work in linux not for windows.. thats why it make an error..

Categories