I have been trying to figure out a way to run Powershell commands inside a Pycharm project where I can make more complicated scripts using Python. I have been searching for an answer but I have only found a few people even ask this question.
I have already verified that my Terminal inside Pycharm is set to PowerShell.
Is there a way to combine a Powershell command inside Python?
If so is there a way to do this inside Pycharm?
I was able to research more about the subprocess module and I was able to find a way to do this inside a python project. Below I put a snippet of a very simple command ran with powershell that outputted what I expected so I can add to that.
import subprocess, sys
computer_name = "L8694C"
p = subprocess.Popen(
["powershell.exe", "Get-ADComputer " + computer_name+ " | Select-Object Name"],
stdout=sys.stdout)
p.communicate()
Related
I am running a (bio)python script which results in the following error:
from: can't read /var/mail/Bio
seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail.
What seems to be the problem here? i doubt it will help as the script doesn't seem to be the problem, but here's my script anyway:
from Bio import SeqIO
from Bio.SeqUtils import ProtParam
handle = open("examplefasta.fasta")
for record in SeqIO.parse(handle, "fasta"):
seq = str(record.seq)
X = ProtParam.ProteinAnalysis(seq)
print X.count_amino_acids()
print X.get_amino_acids_percent()
print X.molecular_weight()
print X.aromaticity()
print X.instability_index()
print X.flexibility()
print X.isoelectric_point()
print X.secondary_structure_fraction()
what is the problem here? bad python setup? I really don't think it's the script.
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python instead of trying to interpret it on its own.
I ran into a similar error when trying to run a command.
After reading the answer by Tamás,
I realized I was not trying this command in Python but in the shell (this can happen to those new to Linux).
Solution was to first enter in the Python shell with the command python
and when you get these >>>
then run any Python commands.
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
Put this at the top of your .py file (for Python 2.x)
#!/usr/bin/env python
or for Python 3.x
#!/usr/bin/env python3
This should look up the Python environment. Without it, it will execute the code as if it were not Python code, but shell code. If you need to specify a manual location of the Python environment, put
#!/#path/#to/#python
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
For Flask users, before writing the commands, first make sure you enter the Flask shell using:
flask shell
I'm working on a script which should run a command in a new subprocess. At the moment im using the python subprocess.Popen() for this. My problem is that I can run commands like "dir" but not a installed program. When I open the cmd prompt and write "program -h" I am getting the normal help outprint. When I try to open it with Popen() I am getting an error that the program can not the found. It is like he is not finding the executable even if the cmd promt can find it when I look for it manually. For the test i used ncat as an example program.
import time
from subprocess import *
import subprocess
execom = "ncat -h" # DOES NOT WORK IN PYTHON BUT MANUALLY IN CMD
execom1 = "ncat -h -e cmd" # DOES NOT WORK IN PYTHON BUT MANUALLY IN CMD
execom2 = "dir" # WORKS
p = Popen(execom, shell=True)
out = p.communicate()[0]
Does someone know how to fix that?
EDIT:
I got the solution with the hint of 2e0byo. I added the paths to the systemvariabels but the system needed an extra restart to pass it. It worked without restart from cmd prompt but not from python script. After restart it works from both now.
Per the comments, the problem is just that ncat isn't in your PATH, so you need to add it:
import os
env = os.environ.copy()
env["PATH"] = r"C:\Program Files (x86)\Nmap;" + env["PATH"]
p = Popen(execom, env=env)
...
See this question for modifying the env.
As to why ncat isn't in your path I really don't know; I don't use Micro$oft Windoze very much. Perhaps someone will be along with a canonical answer to that question, or you can ask it over on superuser and see if someone knows how to set it up. If I needed this to be portable I would just check a bunch of folders for ncat and bail if I couldn't find it.
I would like to include a command to create a 7zip archive withinin a Python script. Since I am working on Windows, I need to pass the command to the powershell console. I am planning to do it with os.system (I am aware that this is not the best way to do it and that I should use subprocess, but I really just need a quick fix and it would not be time effective for me to learn to use a new module in this context).
The following command works if run from the powershell console
&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch
So I recreate the same string within python like this:
cmdl = r"&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch"
The string is interpreted as follow:
"&'C:\\\\Program Files\\\\7-Zip\\\\7z' a -mx=0 X:/myarch.zip X:/myarch"
Now, if I copy-paste the above string within the powershell console, it runs without problems. However, if I run it within python using os.system(cmdl) I got the following error
"The filename, directory name, or volume label syntax is incorrect"
Why is this the case and how can I fix this issue ?
os.system is meant for executing cmd commands, cmd commands can be ran in powershell maybe after all powershell is a bit advanced but I'm sure that you can't run a cmd command in powershell, henceforth your code is not working.
However a creative solution for executing a powershell command from python(not using python) would be to write your command into a .ps file(powershell script)and then run it using os.startfile()(use this code: os.startfile("script.ps"))
In python, we can call any process using subprocess.
I have a situation where I have to work with interactive terminal where I need output of few commands, using python code.
How can I use subprocess module that will open the interactive terminal and I can further bypass few command and get their out to parse them further?
I am able to use subprocess module for 2 different command that where 2nd one is dependent on output of first one like
ps -aux | grep python
first ps -aux can be passed to 1 subprocess obj and that obj will be used as stdin of another subprocess command where grep python will be processed....
you question is not much clear , so i would answer the part which i understand
How can I use subprocess module that will open the interactive terminal and I can further bypass few command and get their out to parse them further?
i have a ubuntu machine and this is the way i invoke a separate terminal and pass command to them
from subprocess import Popen,PIPE
command='who'
command ='"'+command+' '+';read -n1" '
#subitem = Popen(['gnome-terminal','--disable-factory','-x','bash','-c',command],stdin =PIPE)
subitem = Popen(['gnome-terminal','--disable-factory','-x','bash'],stdin =PIPE)
subitem.communicate(input='your command')
You can further play with this using stdin,stdout,communicate method depending on your requirment
I am not even sure if this question is answerable.
Basically in my game I am using the colorama features to make it look nice, but the colorama features only work when you access python in command prompt, so my question is how I can get python program to run another via command prompt, is this doable or not? I have tried installing win32 but that is in python 2 format and I am using 3.4 so I was getting syntax errors that I wasnt sure how to fix.
I am not sure why is this happening, I mean, colorama not working without starting from prompt.
Perhaps something with environment variables PATH or something.
This is one suggestion, and I am not sure that it will work as we will not be changing the window program is running in, just invoking cmd.exe i.e. command prompt to start within it and start python and your script again.
But it is worth a try:
# Start of your program:
import sys, os
if "started_with_prompt" not in sys.argv:
cmd = 'cmd /C "'+sys.executable+' '+" ".join(sys.argv)+' started_with_prompt"'
os.system(cmd)
sys.exit()
print "the rest of your program"
If this doesn't work, there are tricks that can be used through subprocess module to do the similar thing.
Also, you should look at cmd.exe's help to see whether you should use some other switch than /C to enable environment and/or registry extensions.
But, essentially, you should be able to get the same result by making a shortcut with the command like one in cmd variable, or a batch file that starts Python. Like this:
#echo off
cmd /C "C:\Python27\python.exe path_to_your_script.py"
I think both would work, but somehow that you wouldn't like this solution.
Well, I think that shortcut would need a full path to cmd.exe which is:
C:\Windows\system32\cmd.exe
Let me know if it doesn't work.