Running python 2 code within a python 3 file - python-3.x

Is there a way to run python 2 code within a python 3 file?
I have to use a function that is coded in python 2 and is located in a python 2 file. But i need to import it and use the function within a python 3 file. Is is possible to run that function is like a python 2 mode?

It is not possible to run Python 2 code with Python 3, at least not in general. Although converting by hand is fairly straight-forward.
If you have long files you should also consider using 2to3 which will apply the needed fixes to make your code run with Python 3.
If you already have Python 3 installed you simply have to run the following in your terminal.
2to3 your_file_name.py
Note that sometimes 2to3 will be unable to transpile from Python2 to Python3. If it notices it, it will give you warnings and indicate what lines you have to fix manually.
Although, it can also happen that 2to3 doesn't even notice the output code will not work. This is what happened in the example you gave me in the comments:
input('Type text here: ').encode('utf-8').encode('hex')
This will not work in Python3 for reasons that you can explore here.
The reason 2to3 doesn't realize it is because this is actually syntactically perfectly valid code. And actually you could foreshadow input or str.encode in a way that would make this working code.
In conclusion, sometime you have to read the error and fix the code yourself.

Related

Do I need multiple run configurations - one per Python file - in Pycharm even though the only difference between them is the script?

I created a Python project in Pycharm which contains multiple Python files. As of just now, I need to create a run configuration for each Python file in my project, even though they're all the exact same - with the exception of the script.
This seems unnecessary and laborious and I would love to just use one run configuration for multiple Python files.
That said, I'm a novice Python programmer just getting started and so still unfamiliar with large parts of the language.
My Project Files:
My Run Configuration - Used for all Python files:
Some Research Carried Out
I've searched for a solution and explanation to this, but have been unable to find anything. Some of the places I've tried:
JetBrainsTV on youtube (https://www.youtube.com/watch?v=JLfd9LOdu_U)
JetBrains Website (https://www.jetbrains.com/help/pycharm/run-debug-configuration-python.html)
Stack Overflow
I hope there is sufficient detail here, if not I'd be happy to elaborate.
If those files are independent and you have nothing specific to them, then I see two simple ways of running them:
You don't have to manually create a run configuration for every file. You can just Right-Click on the file in the project tree and click "Run "
You can use the Terminal and run them files using the python interpreter as needed.
I was facing a similar situation when I started competitive programming. In my case I wanted to redirect my Test Cases from an input.txt file rather than manually typing the test cases for every run of my code. Using the above solution was not feasible, as I would need to manually change the Script Path and Redirect Input path in the Run Configuration window for every script I was running.
So what I wanted was, one run configuration, that would run all the scripts with Redirect Input path being set to input.txt.
To do that,
I created a main.py file with the following content:
import sys
if __name__ == '__main__':
fname = sys.argv[1]
exec(open(fname).read())
This main.py file is going to run my other python scripts.
Created this run configuration for the main.py file.
Now, every time I needed to run any code, with the code window open, ran this configuration, which actually executed main.py with current file name passed as its argument, which would then also take the inputs redirected from input.txt.
Hope this helps you or anyone trying to run multiple python scripts with a single run configuration in PyCharm.

How to syntax check Python?

I'm writing just a simple Python 3 program (beginner here) and I want to syntax check the code rather than just run it and see errors. How can I do this?
I've done python3 -m py_compile sender.py but nothing changes or is displayed. I'm using version 3.5.2 in Ubuntu, and sender.py is in the directory that I'm currently in.
There are some Python editors than can do this.
For example, Spyder and PyCharm.
They highlight the code segments that have problems.
If you are looking for tools similar to regular compilers, then you can have a look at this stackoverflow question and this with good answers.

How do I use output from SPARC solver as input to a python file?

My question: I need to save the output from a SPARC solver (which is currently appearing as text in the terminal) as a variable in my Python code. How can I do this?
Quick note: SPARC is a solver used for ASP (answer-set-programming) files - just mentioning this so that people don't get confused and think I am referring to asp.net.
I am running a Python file and an ASP file (in query mode) simultaneously, in the same terminal, using the command python pythonfile.py | java -jar sparc.jar aspfile.sp. Output from the python file in the form of sys.stdout.write() is being redirected as the input to the SPARC solver; i.e. the text I output becomes the query that is solved using my ASP code. This is working, and generating the output I want, but I can't figure out how to use that output in my Python code.
This is a follow-up to another question I have asked, found here. In that question I was trying to find out how to run an ASP file from my C++ code. I went with option 2 in the answer I was given, and am using redirected stdout with the two files running as separate processes. Please note one major change since the original question: I am now using Python instead of C++.
Further details if required: My Python version is 2.7 and my operating system is Ubuntu 14.04. I don't think it's relevant but, in case it is, you should know that my Python code is also being used to control a Gazebo Turtlebot simulation, and I am using ROS Indigo to run that simulation. I won't post my code unless someone requests it, as I just want an idea of what method I could use (I can't find anything that works on the internet), rather than needing my code debugged / assistance writing it. However I will post below an example of what is output to the terminal when my code runs, as this is the information I am trying to 'capture'.
SPARC V2.52
program translated
?- yes
?- no
It is the answers 'yes' and 'no' that I want to save as variables in my Python file.
SOLUTION:
For anyone wanting to do the same thing, I followed the answer provided by CaptainTrunky.
First I run the command python pythonfile.py | java -jar sparc.jar aspfile.sp > sparc.out, saving the SPARC output to the text file sparc.out.
Then I run python outputParser.py to run a script that prints the contents of the text file, allowing me to check that I'm manipulating the data correctly. The script is very simple:
lines = [line.strip('?- ') for line in open('sparc.out')]
lines = [line.strip('\n') for line in lines]
print lines
You can use python to read from sys.stdin with a script similar to the following (filter.py):
import sys
for line in sys.stdin.readlines():
if line.startswith('?- '):
print line.strip()
Then invoke your pipeline like this:
python pythonfile.py | java -jar sparc.jar aspfile.sp | python filter.py
I would suggest you do dump SPARK output to text file and then to parse it with you tool.
Write a shell script that does it for you:
python pythonfile.py | java -jar sparc.jar aspfile.sp > spark.out
python parse_out.py spark.out

How can I run my program without using PyCharm?

I have to finish the program on which I worked six months. This is my very first program.
I designed with PyCharm and I have a database and several module.
How can I run my program without using PyCharm?
Based on the fact that you are working on this project for the last 6 months, my guess is that you were running it through PyCharm. In most cases when you run your project through PyCharm you can see that on PyCharm "Run" console the first line logged is something like that:
/path/to/setup/bin/python<version> path/to/your_project/file_contains_main.py --argumnent1=value1 --argumnent2=value2...
Scenario 1
If you see something like that, then you can copy your project in a system that has python installed and run the same file_contains_main.py as below:
python path/to/your_project/file_contains_main.py --argumnent1=value1 --argumnent2=value2...
Some more details for Windows here and for Linux here.
Scenario 2
If you do not see the command above logged in PyCharm then you may find this solution more appropriate.

Novice with Python

I have just downloaded Python 3.3.2 to use on windows7 and run the msi file to install. After installation I have tried using the prog only to find that every time I run my initial print 'hello world' it keeps reporting a syntax error.
I have tried both single and double quotes but each time reports a syntax. It will add say 8 + 9 and return the answer but no joy with using a print statement.
I have tried both the shell and a new window but without success.
Any advice please much appreciated.
If you are using Python 3.x, you have to do print('hello world').
In Python 2.x, print was a statement, like if, for, etc. Now it is a function, thus the ().
You're probably using instructions for a python-2 program, where print was a statement, rather than a function. In python >= 3, you have to do print(something), rather than just print something.

Resources